lua如何实现 静态变量,多次调用同一个函数时,只初始化一次指定的变量值 没啥分,谢谢帮忙

比如
我这里要多次调用test()函数

function test()
local i=0;
if (i<5) then
i=i+1
end;
end;

在Lua 中有两种比较常用的方法 实现 类似 C语言 static 变量的方法

其中利用闭合函数 是《Lua程序设计》(《Programming in Lua》)推荐用法

 


--利用全局变量实现 static variable
local function staic_test()
    n = n or 0;
    n = n + 1;
    return n;
end
print(staic_test())
print(staic_test())

--利用闭合函数 (closure) 实现 static variable
local function staic_test2()
    local i = 0;
    return function()
              i = i + 1;
              return i;
           end
end
staicor = staic_test2();
print(staicor())
print(staicor())

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-25
1、把内容单独放一个文件里lua文件里
local i = 0
function test()
if (i<5) then
i=i+1
end;
end;
2、或者写个生成函数
function create_test()
local i = 0
return function() if(i<5) then i=i+1 end end
end
test = create_test()
然后多次调test就行了。本回答被提问者采纳
相似回答