lua 的栈与内存限制

2018-05-02 12:12编辑本页

在使用动态生成的 lua 代码时,往往要注意 lua 在栈与内存上的限制。结论先放在前面:

结论以 lua 5.1.5 版本(ubuntu 官方发行版)在 ubuntu 18.04 的实际运行为准

  • 一个lua文件不能超过 262144 个常量
  • 一个控制结构不能超过 32895 个栈
  • upvalue数量不能超过 60 个
  • Lua 的每个函数(function)中不能超过 200 个本地变量

本篇文章使用 tt2 技术, 并使用 Template::Tools::tpage 提供的命令行 tpage 来生成 lua 代码

一个lua文件不能超过 262144 个常量

其中 262144 = 2^18^

tt2 代码

1
2
3
4
5
[% SET array = [1..262144] %]

local a = {
    "[% array.join("\", \"") %]"
}

lua 代码

生成的 lua 代码 gist 链接(文件较大): https://gist.github.com/xiaocang/cd947e57cdb6d16b83d7bdc9c4d0cecd#file-too_much_constant-lua

执行结果

1
2
$ lua too_much_constant.lua
lua: constant table overflow

源码定位

TODO


一个控制结构不能超过 32895 个栈

其中 32895 = 2^15^ + 2^7^ - 1

tt2 代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[% DEFAULT max = 32895 %]

if
[% FOREACH i IN [1..max] -%]
    ([% i %] > 0) [% IF i < max %] and [% END %]
[%- IF i % 10 == 0 %]
[% END -%]
[% END %]
then
    print("ok")
end

lua 代码

生成的 lua 代码 gist 链接(文件较大): https://gist.github.com/xiaocang/99a5b636694bab0fd870c17ef97fa472#file-control_pattern_too_long-lua

执行结果

1
2
$ lua control_pattern_too_long.lua
control_pattern_too_long.lua:3297: control structure too long near '<eof>'

源码定位

TODO


upvalue数量不能超过 60 个

tt2 代码

1
2
3
4
5
6
7
8
9
[% FOREACH i IN [1..200] -%]
local a_[% i %]
[% END %]

function closure()
    [% FOREACH i IN [1..61] -%]
    a_[% i %] = 0
    [% END %]
end

lua 代码

生成的 lua 代码 gist 链接(文件较大): https://gist.github.com/xiaocang/baf52c6e7fffa31d684ad55ddfc47867#file-too_much_upvalue-lua

执行结果

1
2
$ lua too_much_upvalue
lua: stdin:264: function at line 203 has more than 60 upvalues

源码定位

TODO


Lua 的每个函数(function)中不能超过 200 个本地变量

tt2 代码

1
2
3
4
[% FOREACH i IN [1..201] -%]
local a_[% i %]
[% END %]
print("ok")

lua 代码

生成的 lua 代码 gist 链接(文件较大): https://gist.github.com/xiaocang/f4fd0b56bbdec00e4794e661b0ffd994#file-variables_in_function-lua

执行结果

1
2
$ lua variables_in_function.lua
main function has more than 200 local variables

源码定位

from lua5.2.2 src/lparser.c line 30-32

1
2
3
/* maximum number of local variables per function (must be smaller
   than 250, due to the bytecode format) */
#define MAXVARS     200

除另有声明外 本博客文章均采用 知识共享(Creative Commons) 署名 4.0 国际许可协议 进行许可 转载请注明原作者与文章出处


标签: lua

点击加载Disqus评论
Creative Commons © 2013 — 2023 xiaocang | Theme based on fzheng.me & NexT | Hosted by Netlify