leevis.com
leevis.com copied to clipboard
lua的坑
记录一些开发过程容易犯错的地方。
- 和其他语言不通lua的下标是从1开始的。
- lua中只有false和nil是假。0也是真。因此
if #str then这样的判断没有意义。 - #tab 的操作,tab中不能有空洞。例如。
a = {1,2,3,4,5}; a[2]=nil; #a是1而不是4. - tab的空洞还影响unpack、ipairs、select('#', tab)。
- xpcall 在lua5.1和lua5.3、luajit不一致。
do
local xpcall_52 = xpcall(
function(x)
assert(x == 1)
end,
function()
end,
1)
if not xpcall_52 then
-- No support for extra args, so need to wrap xpcall
local _xpcall = xpcall
local unpack = unpack or table.unpack -- luacheck: ignore
xpcall = function(f, eh, ...)
local args = { n = select("#", ...), ...}
return _xpcall(
function()
return f(unpack(args, 1, args.n))
end, eh)
end
end
end