首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Lua 與 C 交互實戰:Table 返回、多返回值、Table 元素刪除三大核心技巧

     編輯:關於C語言

場景背景

使用 Lua 編寫遊戲服務器邏輯,需頻繁進行 Lua ↔ C 交互。記錄三個高頻問題的標準解法。

問題一:C 函數返回 Lua Table

對應 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;
}

關鍵 API 說明

  • lua_newtable:創建空表並壓入棧頂
  • lua_gettop:獲取棧頂索引,作為表的引用
  • lua_setfield(L, idx, key):從棧頂取值,設置表idx的字段key,彈出值
  • 返回值 1 告訴 Lua VM 棧頂有 1 個返回值

問題二:C 函數返回多個值

對應 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() 接收。

問題三:Lua 中刪除 Table 元素

單個鍵刪除

local t = {}
t.hello = "hello"
t[1] = 100

-- 刪除鍵 "hello"
t.hello = nil

-- 刪除鍵 1
t[1] = nil

清空整個 Table

-- 方法 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 端對應
返回 Tablelua_newtable + lua_setfield + return 1return {key=val}
多返回值依次 push + return nreturn v1, v2, v3
刪除元素無需 C 介入t[key] = nil

掌握這三個模式,可覆蓋 90% 以上的 Lua-C 交互場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved