$ cc -o call_lua_script call_lua_script.c -I /usr/local/include/ -L /usr/local/lib/ -llua $ ./call_lua_script In C, calling Lua This is comming from lua Back in C again
if (lua_pcall(L, 0, 0, 0)) error_exit(L, "lua_pcall failed");
printf("In C, calling Lua->tablehandler()n"); lua_getglobal(L, "tablehandler"); lua_newtable(L); // Push empty table onto stack, table now at -1 lua_pushliteral(L, "firstname"); // Puah a key onto stack, table now at -2 lua_pushliteral(L, "Veinin"); // Puash a value onto stack, table now at -3 lua_settable(L, -3); // Take key and value, put into table at -3, then pop key and value so table again at -1
if(lua_pcall(L, 1, 1, 0)) // Run function. error_exit(L, "lua_pcall failed");
printf("============ Back in C again, Iterating thru returned table ============n");
lua_pushnil(L); // Make sure lua_next starts at beginning constchar *k, *v; while(lua_next(L, -2)) { // Table location at -2 in stack v = lua_tostring(L, -1); k = lua_tostring(L, -2);
lua_pop(L, 1); // Remove value, leave in place to guide next lua_next().
printf("%s = %sn", k, v); }
lua_close(L);
return0; }
相关函数解析
1.表参数传递惯用手段
1 2 3 4
lua_newtable(L); // Push empty table onto stack, table now at -1 lua_pushliteral(L, "firstname"); // Puah a key onto stack, table now at -2 lua_pushliteral(L, "Veinin"); // Puash a value onto stack, table now at -3 lua_settable(L, -3); // Take key and value, put into table at -3, then pop key and value so table again at -1
对于 C 层代码,可以通过 lua_newtable 函数创建一张空表,并将其压栈,该函数它等价于 lua_createtable(L, 0, 0)。 然后调用 lua_pushliteral 把键和值分别压入栈中,并通过 lua_settable 把 key 和 value 放入 table 中,做一个等价于 t[k] = v 的操作,在操作完成后,这个函数会将键和值都弹出栈。
2.表返回值处理
当 C 调用 Lua 函数返回结束时,它把返回值放在了栈上。当返回值是一个 table 时,索引表格的元素就不那么容易了。对于 table ,在返回 C 时,这个 table 在堆栈的顶部,下面的是访问这个 table 的惯用方法:
1 2 3 4 5 6 7 8 9 10
lua_pushnil(L); // Make sure lua_next starts at beginning constchar *k, *v; while(lua_next(L, -2)) { // Table location at -2 in stack v = lua_tostring(L, -1); k = lua_tostring(L, -2);
lua_pop(L, 1); // Remove value, leave in place to guide next lua_next().