I recently posted a thread asking for some help, and got some great responses. So I wanted to give back by sharing a trick I learned while working on my current game project which others may find useful.
I found myself reading writing lots of calls like
Code: Select all
love.graphics.setColor(96, 85, 64)
Unless you are really familiar with your RGB values---and I am not---you may not know that creates a dark orange color. I wanted to create named color constants. So at first I created a table like so:
Code: Select all
Colors = {}
Colors.darkOrange = { 96, 85, 64 }
Colors.yellow = { 196, 196, 0 }
-- And so on.
The Lua function unpack() lets you take an array/table and expand its values as the parameters to a function call. So this let me go back and start writing
Code: Select all
love.graphics.setColor(unpack(Colors.yellow))
Except I felt calling unpack() every time was tedious on its own. Enter the usefulness of metatable functions. You can change the __index() function for a table to automatically unpack values. So I returned to my table of colors and added this:
Code: Select all
Colors.__index =
function (table, key)
local value = rawget(table, key)
if value ~= nil then
return unpack(value)
else
return nil
end
end
Now writing Colors.yellow is the same as unpack(Colors.yellow). This let me return to my original code and replace it with the more readable (in my opinion)
Code: Select all
love.graphics.setColor(Colors.darkOrange)
.
Just a simple trick I wanted to share that maybe some of you will find useful.