下面的demo,主要演示 C如何访问 Lua中 函数、变量。
lua代码
function add(x,y)
print("add")
return x + y
end
width = 100
height= 200
background = {r=0, g=0, b=1}
C代码
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
lua_State* L;
int luaadd(int x, int y)
{
int sum;
/*调用函数名称*/
lua_getglobal(L,"add");
/*第一个参数*/
lua_pushnumber(L, x);
/*t第二个参数*/
lua_pushnumber(L, y);
/*调用函数两个参数一个返回值.*/
lua_call(L, 2, 1);
/*获取返回值*/
sum = (int)lua_tonumber(L, -1);
/*清空栈*/
lua_pop(L,1);
return sum;
}
//获取宽度和高度
int GetParam(int *width, int *height)
{
lua_getglobal(L, "width");
lua_getglobal(L, "height");
*width = (int)lua_tonumber(L, -2);
*height = (int)lua_tonumber(L, -1);
lua_pop(L,1);
return 0;
}
#define MAX_COLOR 255
int getfield (const char *key)
{
int result;
lua_pushstring(L, key);
lua_gettable(L, -2); /* get background[key] */
//if (!lua_isnumber(L, -1))
// error(L, "invalid component in background color");
result = (int)lua_tonumber(L, -1) * MAX_COLOR;
lua_pop(L, 1); /* remove number */
return result;
}
void GetTable()
{
lua_getglobal(L, "background");
int red = getfield("r");
int green = getfield("g");
int blue = getfield("b");
printf("r:%d,g:%d,b:%d",red,green,blue);
}
int main()
{
int sum;
/*初始化lua*/
L = lua_open();
/*加载 Lua lib*/
luaL_openlibs(L);
/*打开hello.lua脚本*/
luaL_dofile(L, "hello.lua");
sum = luaadd(10, 15);
printf("The sum is %d \n",sum);
int width,height;
GetParam(&width,&height);
printf("%d,%d",width,height);
GetTable();
//关闭lua
lua_close(L);
return 0;
}