3 ms·
Some things to add: * Lexical scoping * Tail-call optimization * First class functions / closures Lua is not a functional programming language but I tend to h
by copx 13y ago
Some things to add:
* Lexical scoping
* Tail-call optimization
* First class functions / closures
Lua is not a functional programming language but I tend to have a large number of closures and recursive functions in my Lua code. Lua's limited feature set means that you end up using closures as a replacement for things which are special features in other language.
Here is an example of a closure doing the job of C/C++'s function-scope static:
View.Move = (function()
local move = {
[Direction.up] = View.Up,
[Direction.left] = View.Left,
[Direction.right] = View.Right,
[Direction.down] = View.Down
}
return function(self, direction) move[direction](self) end
end)()
Note that a closure is more efficient than function-scope static here. The static requires a "is initialized?" check every time the function gets called, the closure does not.
- anonymoushn 13y agoThe features mentioned, along with coroutines and coroutine.clone, allow the creation of more or less any control flow the user could want. It's a total breeze to use. Is Closure(function ... end) really an improvement over the normal IIFE look of (function ... end)()?
- copx 13y ago>Is Closure(function ... end) really an improvement over the normal IIFE look of (function ... end)()? Now that you say it.. no, it's not. Changed.
- pygy_ 13y agoBetter still: do local move = { [Direction.up] = View.Up, [Direction.left] = View.Left, [Direction.right] = View.Right, [Direction.down] = View.Down } function View.move(self, direction) move[direction](self) end end
- Derbasti 13y agoLua's function definition syntax is really the best one I have seen yet. One simple statement that combines all the flexibility of lambda and def (in Ruby/Python-speak). I wish Ruby and Python had a powerful statement like that.
- kazagistar 13y agoRandom performance note: in the default lua interpreter, the fastest objects are the ones implemented as closures. Unfortunately, it has higher memory requirements and is rather ugly.