lua-users home
lua-l archive

Think different

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Ok so this post is just a way to show the true beauty of Lua: there are MANY ways to do a thing.
First: Locals.
We technically don't need the local keyword, except that it's nice for block-level scoping.
Function-level locals can be declared on the function:
function f(l1, l2, l3, ...)
 l1, l2, l3, ... = nil
 -- Use l1, l2, l3, ... as locals
end
Modules can be done this way too:
return (function(f1, f2, f3, l1, l2, l3, ...)
 function f1(...) end
 function f2(...) end
 function f3(...) end
 return {f1 = f1, f2 = f2, f3 = f3}
end)(nil, nil, nil, nil, nil, nil, ...)
Second: The comma operator.
C has the comma operator. We can emulate it with "and" and "or".
x = (x or true) and (y or true) and (z) -- x = z
Or select.
x = select(-1, x, y, (z)) -- x = z
Third: Stacks.
There are 2 ways to do a stack object in Lua: Either you use tables (PITA), or you use coroutines: (code may or may not be correct - other examples available online)
local function stackinternals(op, x, ...)
 if op == "push" then
 local a, b = coroutine.yield()
 return stackinternals(a, b, x, ...)
 elseif op == "pop" then
 local a, b = coroutine.yield(...)
 return stackinternals(a, b, select(2, ...))
 elseif op == "peek" then
 local a, b = coroutine.yield(...)
 return stackinternals(a, b, ...)
 end
end
function newstack(...)
 local co = coroutine.wrap(function(...)
 local a, b = coroutine.yield()
 return stackinternals(a, b, ...)
 end)
 co(...)
 return co
end
(It's also A LOT faster than a table-based implementation, and if done in-thread instead of using coroutines it's even faster!)
[etc]
So what are your favorite ways to do something, and why do you like it?
--
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.

AltStyle によって変換されたページ (->オリジナル) /