3 ms·
Lua's weird return values are basically just exposing the fact that it's a stack-based VM and letting the user take advantage of that. foo(1, return_two_values(
by plorkyeran 13y ago
Lua's weird return values are basically just exposing the fact that it's a stack-based VM and letting the user take advantage of that. foo(1, return_two_values(arg), 2) pushes 1 onto the stack, pushes arg onto the stack, calls return_two_values (which pops one value from the stack and pushes two new ones), pushes 2 onto the stack, and then calls foo, resulting in foo being called with four arguments.
With this design you get zero-overhead (you save the construction of a table) multiple return values for free, since it simply requires a trivial bit of syntax and no error checking to verify that a function only left zero or one values on the stack. Lists aren't exposed as concrete things that can be passed around because the really aren't things at all.
- anonymoushn 13y agoActually, foo(1, return_two_values(arg), 2) will call foo with only three values. The , truncates (or extends) the left expression to exactly one value. > return (function() end)(), 5 nil 5 > return (function() return 1,2,3,4 end)(), 5 1 5 > return 5, (function() end)() 5 > return 5, (function() return 1,2,3,4 end)() 5 1 2 3 4 > return 5, (function() return nil end)() 5 nil