|
Hey list,
I was going through archives and read this now
ancient post by Diego Nehab:
I know bumping old posts is very (extremely?) bad form, but with
talk about Lua 6 thought I might resurrect
the idea anyway and see if interest has changed. Let this post die a natural
death if sentiment hasn't changed :). The idea is
easy enough to implement, and with a small optimization (to recognise vararg
appends / vararg pops) some functions that are currently impossible to write in
O(n) time Lua become possible. The vm would require a second value stack for
arguments, but that's possibly a better solution then the current
varargs-between-call-frames anyway imo. Simplifies callinfos somewhat, removing
the need for a func stkid.
Here's a couple of ways to abuse the idea which I
quite like :)
(P.S. I did a quick look for lua wish list via
google so as to not annoy the list, but only found a page which discourages
syntax changes... are there any generic wish list pages?)
Current Lua:
-- O(n^2) algorithm
function sumargs(...)
local res = 0
for i = 1, select("#", ...) do
res = res + select(i,
...)
end
return res
end
With ... as lvalue:
-- O(n) algorithm
function sumargs(...)
local res = 0
while ... do
local x, ... = ...
res = res + x
end
return res
end
Current Lua:
function dostuff()
local res1, res2, res3
lock()
if cond() then
res1, res2 =
get2res()
else
res1, res2, res3 =
get3res()
end
unlock()
return res1, res2, res3
end
With ... as an lvalue:
function dostuff()
lock()
if cond() then
... =
get2res()
else
... =
get3res()
end
unlock()
return ...
end
Current Lua:
-- O(n^2) algorithm - only way to rewrite unpack in
lua
-- (could be made O(n) time by having the compiler
recognise append return tailcalls)
-- -- Coincidentally, deep recursive calls can be improved by this
line change in lvm.c:-- if
(L->openupval) luaF_close(L, base);
-- to
-- if
(L->openupval && cl->p->p) luaF_close(L,
base);
-- As at any time there's often an open
closure, but rarely is the creator the running function
function auxunpack(tab, start, len)
if start <= len then
return tab[start], unpack(tab,
start+1, len)
end
end
function unpack(tab, start, len)
return auxunpack(tab, start or 1, len or
#tab)
end
With ... as lvalue:
-- O(n) algorithm
-- to expand ... requires writing result
backwards
function unpack(tab, start, len)
for i = len or #tab, start or 1, -1
do
... = tab[i], ...
end
return ...
end
- Alex |