1. 基础:
Lua的一项重要用途就是作为一种配置语言。现在从一个简单的示例开始吧。
--这里是用Lua代码定义的窗口大小的配置信息
width = 200
height = 300
下面是读取配置信息的C/C++代码:
#include
#include
#include
#include
#include
void load(lua_State* L, const char* fname, int* w, int* h) {
if (luaL_loadfile(L,fname) || lua_pcall(L,0,0,0)) {
printf("Error Msg is %s.\n",lua_tostring(L,-1));
return;
}
lua_getglobal(L,"width");
lua_getglobal(L,"height");
if (!lua_isnumber(L,-2)) {
printf("'width' should be a number\n" );
return;
}
if (!lua_isnumber(L,-1)) {
printf("'height' should be a number\n" );
return;
}
*w = lua_tointeger(L,-2);
*h = lua_tointeger(L,-1);
}
int main()
{
lua_State* L = luaL_newstate();
int w,h;
load(L,"D:/test.lua",&w,&h);
printf("width = %d, height = %d\n",w,h);
lua_close(L);
return 0;
}
下面是针对新函数的解释:
lua_getglobal是宏,其原型为:#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s))。
每次调用这个宏的时候,都会将Lua代码中与之相应的全局变量值压入栈中,第一次调用时将全局变量"wi