[Lua] 纯文本查看 复制代码 #include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
// 1. 定义C函数,符合 lua_CFunction 原型
static int myfunc_return_two_tables(lua_State *L) {
// --- 创建并填充第一个Table ---
lua_newtable(L); // 压入第一个新表 (索引 -1)
lua_pushstring(L, "name"); // 压入键 "name" (索引 -2)
lua_pushstring(L, "Table One"); // 压入值 "Table One" (索引 -1)
lua_settable(L, -3); // 弹出键和值,设置到第一个表中
// 此时表仍在栈顶 (索引 -1)
// --- 创建并填充第二个Table ---
lua_newtable(L); // 压入第二个新表 (索引 -1,第一个表现在在 -2)
lua_pushstring(L, "id"); // 压入键 "id"
lua_pushinteger(L, 2); // 压入值 2
lua_settable(L, -3); // 设置键值对到第二个表
// 2. 此时,栈中有两个表:第一个表在索引 -2,第二个表在索引 -1
// 3. 返回2,表示有两个返回值
return 2;
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// 将C函数注册为Lua的全局函数
lua_register(L, "get_two_tables", myfunc_return_two_tables);
// 执行Lua代码来测试
const char *lua_code =
"local t1, t2 = get_two_tables()\n"
"print('第一个表:', t1.name)\n"
"print('第二个表:', t2.id)";
if (luaL_dostring(L, lua_code) != LUA_OK) {
fprintf(stderr, "错误: %s\n", lua_tostring(L, -1));
}
lua_close(L);
return 0;
}
|