Functions are first class variables in Lua and Python
Archive - Originally posted on "The Horse's Mouth" - 2012-04-13 22:25:42 - Graham Ellis
I've been training in Lua and Python this week - and the two languages are very diferent, but in many ways they're also much the same. Both languages are slim (ie not bloated with facilities). For example neither supports the ++ operator which those of us who do a lot of coding in Perl, PHP, C and C++ are s familiar with.
One of the other big surprises for newcomers to both Python and Lua is that functions (named blocks of code) are themselves first class variables within the same name space and storage space. On one hand this means that you can't have data stored with the same name as a function (but then you don't want to anyway), but on the other hand this gives you a truely refreshing way of doing lots of dynamic coding which can be really exciting too. (And dangerous - it gives you the tools to do really silly things).
Let me give you an example that shows you the way you can manipulate code:
Defining two functions in Lua:
function footie(some)
return math.floor(some / 11)
end
function boat(more)
return math.floor(more / 9)
end
footie and boat are regular first class variables, so I can put them into a table (Lua's collection structure - a bit like a list or an array):
games = {footie, boat}
And I can them loop through them, running each of them in turn using a pair of round brackets to say "run this as a function":
for _,play in pairs(games) do
teams = play(staff)
print (teams)
end
Complete source example [here]. And a complete Python example [here].