Spreadsheet #3
🦔 🦔 🦔
What if Spreadsheet #2 was Lua? You get Spreadsheet #3.
Here we get to use one of the coolest parts of Lua: metatables. You can set all sorts of properties on objects using this way – what happens when you call or index them, what happens when you assign, what happens when you use operators, and so on.
The special __index
metatable method will be called whenever you try to access a non-existent table property – so if I try to do foo.bar
when bar
doesn't exist, __index
will be called, giving me a chance to resolve its value.
Now, Lua has a global table, _G
. This table holds all the global variables – think JavaScript's window
.
And you can set a metatable on that as well. This means that we can use metatable tricks like __index
with global variables.
To make things even cooler, Lua lets you evaluate some code using load()
, letting you set that code's environment. This means we can craft our own environment that'll automatically resolve dependencies for us whenever the cell formula tries to access any other cell, all while keeping each cell isolated from one another since they all have their own unique environments.
Pretty neat!
I originally wrote this as a more JavaScript-intensive thing, where each cell got its own Lua interpreter, efficiency be damned. But the more I looked at metatables, the more I started to realize how powerful they are.