使用 Lua 編寫遊戲服務器邏輯,需頻繁進行 Lua ↔ C 交互。記錄三個高頻問題的標準解法。
對應 Lua 代碼:
function return_table()
local t = {}
t.result = true
t.data = "hello"
return t
end
C 實現:
int tableReturnTable(lua_State *L) {
// 1. 創建新表,棧頂索引為 table_index
lua_newtable(L);
int table_index = lua_gettop(L);
// 2. 設置字段 result = true
lua_pushboolean(L, true);
lua_setfield(L, table_index, "result");
// 3. 設置字段 data = "hello"
lua_pushstring(L, "hello");
lua_setfield(L, table_index, "data");
// 4. 返回 1 個值(該表)
return 1;
}
lua_newtable:創建空表並壓入棧頂lua_gettop:獲取棧頂索引,作為表的引用lua_setfield(L, idx, key):從棧頂取值,設置表idx的字段key,彈出值1 告訴 Lua VM 棧頂有 1 個返回值對應 Lua 代碼:
function mult_return()
return "hello", 100, true
end
C 實現:
int mult_return(lua_State *L) {
lua_pushstring(L, "hello"); // 第 1 個返回值
lua_pushnumber(L, 100); // 第 2 個返回值
lua_pushboolean(L, true); // 第 3 個返回值
return 3; // 返回 3 個值
}
Lua 調用約定:C 函數將返回值依次壓入棧,返回整數 n 表示棧頂 n 個值為返回值。調用者可用 a, b, c = func() 接收。
local t = {}
t.hello = "hello"
t[1] = 100
-- 刪除鍵 "hello"
t.hello = nil
-- 刪除鍵 1
t[1] = nil
-- 方法 1:pairs 遍歷刪除(Lua 5.1+ 安全)
for k in pairs(t) do
t[k] = nil
end
-- 方法 2:table.foreach(舊版本兼容)
table.foreach(t, function(k, v) t[k] = nil end)
-- 方法 3:直接賦新表(最簡潔,但會改變引用)
t = {}
| 操作 | C API 關鍵點 | Lua 端對應 |
|---|---|---|
| 返回 Table | lua_newtable + lua_setfield + return 1 | return {key=val} |
| 多返回值 | 依次 push + return n | return v1, v2, v3 |
| 刪除元素 | 無需 C 介入 | t[key] = nil |
掌握這三個模式,可覆蓋 90% 以上的 Lua-C 交互場景。