Game Development Reference
In-Depth Information
Expanding Tokenized Variables
In many RPG-style games, while the story is unfolding, you may be asked for your name, after which
the story continues using your name from that point forward. One way to manage this is to store the
name in a variable and templatize it using the printf function, as follows:
printf("The %s Wizard looks at you and says, %s, you are worthy", wizardAdjective, yourName)
This works, but it requires that you place the variables at precise locations so that they match
each of the tokens required. If you missed the wizardAdjective , you would receive an error as
the code requires two additional arguments, not one. If you had them accidentally swapped, and
yourName was Damon and the wizardAdjective was apprentice ,then it would display as The Damon
, instead of the correct output of, The
.
result instead of the Overlord .
return (tmpl:gsub('%$([%a_][%w_]*)',t))
end
You can also use it like this:
print(expandVars('welcome $USER?',os.getenv))
Padding Zeros to a String
In many games, it can be interested to display scores with leading zeros (e.g., 0003 instead of 3)—
for instance, to make the score look like old-style games, many of which used this type of display.
This can be used to create many interesting effects—for example, you could have an odometer-type
display roll the numbers as the score increases.
Here's how you can pad numbers with zeros:
function paddWithZero(theNumber, numOfDigits)
return string.rep("0", numOfDigits - string.len(theNumber)) .. theNumber
end
Getting the Month As a String
There are times when you might want the name of the month as a string, as shown in the code
below. You can also adapt this to have the full names (January, February, etc.), and then return the
first three characters if you want the short name.
 
Search WWH ::




Custom Search