others-how to solve the `loop in gettable` error in lua?
1. Problem
In this post , I will demo how to solve loop in gettable
error when using lua.
Here is the error detail:
/usr/local/bin/lua: ...ects/bswen-demo/src/debug/test_object_create.lua:14: loop in gettable
stack traceback:
...ects/bswen-demo/src/debug/test_object_create.lua:14: in function 'test1'
...ects/bswen-demo/src/debug/test_object_create.lua:36: in main chunk
[C]: ?
the code that caused the problem:
The class in test_object.lua
:
local function init()
local obj = {
root = {},
options = {noreduce = {}}
}
obj._stack = {obj.root, n=1}
return obj
end
local _M = init()
function _M:new()
local obj = init()
obj.__index = self
setmetatable(obj, self)
return obj
end
function _M:text(text)
end
_M.cdata = _M.text
_M.__index = _M
return _M
Actually , you can use any type of lua class to test this problem.
The client:
local handler = require "test_object" -- import the class
local function test1()
for i=1,200 do
handler = handler:new() -- initialize the handler class
handler:text("bbb"..tostring(i)) -- call the function of the class
end
end
test1() -- call the test function
run the above code, we got this error:
/usr/local/bin/lua: ...ects/bswen-demo/src/debug/test_object_create.lua:14: loop in gettable
stack traceback:
...ects/bswen-demo/src/debug/test_object_create.lua:14: in function 'test1'
...ects/bswen-demo/src/debug/test_object_create.lua:36: in main chunk
[C]: ?
2. Solution
change your client as follows:
local function test2()
for i=1,200 do
local handler_good2 = handler:new(i) -- the key point: define the variable using a new name.
handler_good2:text("aa")
end
end
reason: It seems that if you have 100 nested reference in lua, there will be ‘loop in gettable’ error at runtime.
After changing from
handler = handler:new()
to this:
local handler_good2 = handler:new(i)
we are trying to avoid the naming confliction or polution in the lua namespaces.
3. Summary
In this post, I demonstrated how to solve the ‘loop in gettable’ error when using lua. That’s it, thanks for your reading.