本站网址: YippeeSoft开心软件
本文链接: 20070709 LUA 调用 C 变量
20070709 LUA调用 C 变量
http://www.yippeesoft.com
void CTestLuaSpDlg::OnLuaE()
&leftsign;
// TODO: 在此添加命令处理程序代码
int status, result, i;
double sum;
lua_State *L;
/*
* All Lua contexts are held in this structure. We work with it almost
* all the time.
*/
L = lua_open();
luaL_openlibs(L); /* Load Lua libraries */
/* Load the file containing the script we are going to run */
status = luaL_loadfile(L, "\\\\Storage\\\\Program Files\\\\TestLuaSp\\\\add.lua") ;
if (status) &leftsign;
(void)fprintf(stderr, "bad, bad file\\n");
exit(1);
&rightsign;
/*
* Ok, now here we go: We pass data to the lua script on the stack.
* That is, we first have to prepare Lua\’s virtual stack the way we
* want the script to receive it, then ask Lua to run it.
*/
lua_newtable(L); /* We will pass a table */
/*
* To put values into the table, we first push the index, then the
* value, and then call lua_rawset() with the index of the table in the
* stack. Let\’s see why it\’s -3: In Lua, the value -1 always refers to
* the top of the stack. When you create the table with lua_newtable(),
* the table gets pushed into the top of the stack. When you push the
* index and then the cell value, the stack looks like:
*
* <- [stack bottom] — table, index, value [top]
*
* So the -1 will refer to the cell value, thus -3 is used to refer to
* the table itself. Note that lua_rawset() pops the two last elements
* of the stack, so that after it has been called, the table is at the
* top of the stack.
*/
for (i = 1; i <= 5; i++) &leftsign;
lua_pushnumber(L, i); /* Push the table index */
lua_pushnumber(L, i*3); /* Push the cell value */
lua_rawset(L, -3); /* Stores the pair in the table */
&rightsign; 初始化 FOO 数组变量
/* By which name is the script going to reference our table ? */
lua_setglobal(L, "foo"); 设置
/* Ask Lua to run our little script */
result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result) &leftsign;
fprintf(stdout, "bad, bad script\\n");
exit(1);
&rightsign;
/* Get the returned value at the top of the stack */
sum = lua_tonumber(L, lua_gettop(L));
if (!sum) &leftsign;
fprintf(stdout, "lua_tonumber() failed!\\n");
exit(1);
&rightsign;
fprintf(stdout, "Script returned: %.0f\\n", sum);
lua_pop(L, 1); /* Take the returned value out of the stack */ 获得返回值
lua_close(L); /* Cya, Lua */
&rightsign;
– script.lua
– Receives a table, returns the sum of its components.
io.write("The table the script received has:\\n");
x = 0
for i = 1, #foo do
print(i, foo[i])
x = x + foo[i]
end
io.write("Returning data back to C\\n");
return x
原创文章,转载请注明: 转载自YippeeSoft开心软件
本文链接地址: 20070709 LUA 调用 C 变量
历史博文
- 通达信 资金流向 - 2010
- 20080804 GUITOOLKIT 编译 static lib - 2009
- 1018 pecofoods - 2007
- 0131 SIP VC2005 warning C4996 - 2006
- 扩充文件选择对话框的多选能力 - 2005
评论