3 ms·
Lua does TCO and implements it with a special opcode that tracks the number of times a function is called, and you can get an accurate stack dump. function
by spc476 14y ago
Lua does TCO and implements it with a special opcode that tracks the number of times a function is called, and you can get an accurate stack dump.
function r(x)
if x == 1 then
return 1
else
return r(x-1)
end
end
r(100000000)
[spc]saltmine:/tmp>lua t.lua
^Clua: t.lua:6: interrupted!
stack traceback:
t.lua:3: in function 'r'
t.lua:6: in function <t.lua:2>
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
...
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
(tail call): ?
t.lua:10: in main chunk
[C]: ?
[spc]saltmine:/tmp>
But one reason why I like TCO is in writing code to handle protocols. Create a state machine that describes the protocol. Convert each state to a function. Transitions to a another state is a function call. It works something like:
function start()
i = getinput()
if i == A then
return state_A()
elseif i == B then
return state_B()
else
return state_error()
end
end
function state_A()
return state_B()
end
function state_B()
i = getinput()
if i == MORE then
return state_A()
else
return DONE
end
end
function state_error()
return ERROR;
end
Because of TCO, each function call is effectively a GOTO. I've used this method to implement TFTP.