脑灵素片哪里有卖:c中读取Lua的全局变量数组

来源:百度文库 编辑:偶看新闻 时间:2024/05/03 10:01:35
原帖:http://blog.csdn.net/SpiriTRinG/archive/2009/03/14/3990733.aspx

配置实际上是非常简单的,添加好lib和头文件就ok了。

注意如果您是使用动态库,需要配置dll,最好的方式是把dll放在编译目录下,

这样发布您的程序就不会忘记这些杂七杂八的dll了。
Lua文件:luatext.lua

----------------------------------------------------------------------------------

gnum = 1


background = {r=1, g=2, b=3}

tab = {a=44 ,b=33 ,c=22,1, 2, 3, 4, 5, 6, 7, 8, 9, 0}

----------------------------------------------------------------------------------

c文件:lua.cpp

----------------------------------------------------------------------------------

#include
#include
#include

#pragma comment(lib,"lua51.lib")

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
using namespace std;

lua_State *L;

int getGlobal(lua_State *l,char * varname)
{
static int count = 0;
lua_getglobal(l, varname);
return ++count;
}

float getGlobalNumber(lua_State *l ,char * varname)
{
return (float)lua_tonumber (l, getGlobal(l, varname));
}


float getField (const char *key)
{
float result = 0.0f;
lua_pushstring(L, key);
lua_gettable(L, -2);
result = (float)lua_tonumber(L, -1);
lua_pop(L, 1);
return result;
}

float getNumber (const lua_Number num)
{
float result = 0.0f;
lua_pushnumber(L, num);
lua_gettable(L, -2);
result = (float)lua_tonumber(L, -1);
lua_pop(L, 1);
return result;
}

int main (void)
{
////////////////////////////////////////////////////////////////

L = lua_open();
luaL_openlibs (L);
luaL_loadfile(L, "luatext.lua");
lua_pcall(L, 0, 0, 0);

lua_getglobal(L, "background");
cout< cout< cout<
lua_getglobal(L, "tab");
cout< cout< cout< for(int i =1 ; i<=10 ; i++)
cout<

///////////////////////////////////////////////////////////////
lua_close(L);
getchar();
return 0;

}