--lua动态变量名用法,该方法只能定义全局变量
loadstring("a" .. 1 .. " = 8")();
print(a1);--输出a1的结果是8
--还有这种写法也是可以
--循环里可能需要字符和数字拼接,其实等价于_G['a2'] = 10
_G['a'..2] = 10;
print(a2);


--函数调用
function add(a, b)
     return a + b
end

local value = loadstring("return add")()
print(value(1, 2))
--就等于:

function func()
     return add
end
value = func()
print(value(1, 2))


--动态函数
local tabV = { "i", "j", "k"}

local t =[[
    for %s=0, 3 do
        print("%s==".. %s)
    end
]]


for k,v in pairs(tabV) do
    print(k,v)
    all_i = string.format(t, v, v, v)
    local f = assert(loadstring(all_i))
    f()
    --其实简单点直接写成loadstring(all_i)()就行了
end
Copyright © TouchNet 2015 all right reserved,powered by Gitbook最后修订时间: 2022-06-21 09:21:04

results matching ""

    No results matching ""