#
include
<stdio.h>
#
include
<string.h>
#
include
<math.h>
#
include
<lua.h>
#
include
<lauxlib.h>
#
include
<lualib.h>
#
include
<stdarg.h>
#
include
<stdlib.h>
#define MAX_COLOR 255
static
void stackDump(lua_State *L);
static
int l_split(lua_State *L)
{
const
char *s = luaL_checkstring(L, 1);
const
char *sep = luaL_checkstring(L, 2);
const
char *e;
int i = 1;
lua_newtable(L);
while
((e =
strchr
(s, *sep)) != NULL)
{
lua_pushlstring(L, s, e-s);
lua_rawseti(L, -2, i ++);
s = e + 1;
}
lua_pushstring(L, s);
lua_rawseti(L, -2, i);
return
1;
}
int l_map(lua_State *L)
{
int i, n;
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);
n = lua_objlen(L, 1);
for
(i = 1; i <= n; i ++)
{
lua_pushvalue(L, 2);
lua_rawgeti(L, 1, i);
lua_call(L, 1, 1);
lua_rawseti(L, 1, i);
}
return
0;
}
static
int l_sin(lua_State *L)
{
double d = lua_tonumber(L, 1);
lua_pushnumber(L, sin(d));
return
1;
}
double f(lua_State *L,double x, double y)
{
double z;
lua_getglobal(L,
"f"
);
lua_pushnumber(L, x);
lua_pushnumber(L, y);
if
(lua_pcall(L, 2, 1, 0) != 0)
printf(
"call f error\n"
);
if
(!lua_isnumber(L, -1))
printf(
"function f must return a number\n"
);
z = lua_tonumber(L, -1);
lua_pop(L, 1);
return
z;
}
int getfield(lua_State *L,
const
char *key)
{
int result;
lua_getfield(L, -1, key);
if
(!lua_isnumber(L, -1))
printf(
"invalid component\n"
);
result = lua_tonumber(L, -1);
lua_pop(L, 1);
return
result;
}
static
void stackDump(lua_State *L)
{
int i;
int top = lua_gettop(L);
for
(i = 1; i <= top; ++ i)
{
int t = lua_type(L, i);
switch
(t) {
case
LUA_TSTRING:
printf(
"'%s'"
, lua_tostring(L, i));
break
;
case
LUA_TBOOLEAN:
printf(lua_toboolean(L, i) ?
"true"
:
"false"
);
break
;
case
LUA_TNUMBER:
printf(
"%g"
, lua_tonumber(L, i));
break
;
default
:
printf(
"%s"
, lua_typename(L, t));
break
;
}
printf(
" "
);
}
printf(
"\n"
);
}
void load(lua_State *L,
const
char *fname, int *w, int *h) {
if
(luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0))
printf(
"cannot run config.file\n"
);
lua_getglobal(L,
"table"
);
if
(!lua_istable(L, -1))
printf(
"background should be table\n"
);
printf(
"%f\n"
, f(L, 1.1, 2.2));
float red = getfield(L,
"r"
);
float green = getfield(L,
"g"
);
float blue = getfield(L,
"b"
);
printf(
"%f, %f, %f\n"
, red, green, blue);
}
const
char* testfunc =
"t = mysplit(\"hi, hello\", \",\"); print(t[1], t[2])"
;
int main(void)
{
char buff[256];
int error;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
int w, h;
lua_pushcfunction(L, l_sin);
lua_setglobal(L,
"mysin"
);
lua_pushcfunction(L, l_map);
lua_setglobal(L,
"mymap"
);
lua_pushcfunction(L, l_split);
lua_setglobal(L,
"mysplit"
);
if
(luaL_dostring(L, testfunc))
fprintf
(stderr,
"%s"
, lua_tostring(L, -1));
lua_close(L);
return
0;
}