Lua可變參數 “attempt to index global ‘arg’ (a nil value)”


使用Lua可變參數在win包報錯,在Unity上則完全沒問題,win包用的Lua解釋器是luajit,而Unity上用的Lua5.1.
其實是Lua在5.2及后續版本中去掉了arg全局關鍵字,導致在luajit版本中找不到arg而報錯。

在 5.2 之前, Lua 將函數的可變參數存放在一個叫 arg 的表中, 除了參數以外, arg 表中還有一個域 n 表示參數的個數.
到了 5.2 中, 定義函數的時候, 如果使用了 "..." 表達式, 那么語言后台將不會再幫忙打包 "arg" 對象了, 它將直接使用 {...} 用可變參數中的所有值創建一個列表.

新的可變參數推薦用法:

function methodB(...)
      local arg = { ... } --Lua 5.2以后不再支持默認arg參數,{}與...之間要有空格
      print(arg[1], arg[2], arg[3]) -- 注意arg[]中間不能包含nil,需要特殊處理

      print(select(1, ...))
end

function methodA(...)
      methodB(...)
end

在一些比較老的lua文檔手冊上,lua5.2的可變參數用法還未更新,有點誤人子弟。

復習下可變參數概念
The three dots (...) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg. Besides those arguments, the arg table has an extra field, n, with the actual number of arguments collected.

大致意思是:將多個不定數量的參數通過...封裝在table中傳遞,當方法獲取到這些參數時包含隱藏參數arg。

在處理arg打印輸出時,注意nil值,常用的打印方式ipairs不支持數組下標不連續的情況,這種時候就需要引入select,調用select時,傳入一個selector和變長參數,如果selector為數字n,那么select返回它的第n個可變實參,如果是字符串'#'則會返回變長參數總數。

local function args(...)
    if next({...}) then
        -- get the count of the params
        for i = 1, select('#', ...) do
            -- select the param
            local param = select(i, ...)
            print(param)
        end
    else
        print("empty var")
    end
end

args(10, nil, 30)

-- output:
-- 10
-- nil
-- 30

參考:
https://zhuec.gitbook.io/learning-notes/windows-da-jian-xia-lua-kai-fa-huan-jing/5.2+-lua-zhong-de-ke-bian-can-shu


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM