How to use a match to reference a variable?

Post Reply
DarkArtist
Posts: 21
Joined: Sun Dec 15, 2013 12:36 am

How to use a match to reference a variable?

Post by DarkArtist »

Lets say that there are several kinds/colors of potions that you want to keep track of.

The potions are acquired off the corpses of victims as such: You get a green potion from the corpse.

So everytime I get a green potion I want to increment greenCount, red potion redCount, yellow potion yellowCount, etc...

The long way would be something like:
if matches[2]="red" then redCount=redCount+1
elseif matches[2]="green" then greenCount=greenCount+1...

How do I simplify it such that it uses the matched color to refer to the appropriately named variable? i.e. matches[2]Count ?

Thanks!

User avatar
Akaya
Posts: 414
Joined: Thu Apr 19, 2012 1:36 am

Re: How to use a match to reference a variable?

Post by Akaya »

This is how I'd do it. Might be better ways out there...
Code: [show] | [select all] lua
--you'll need a global table to store everything in...
Count = Count or {
  red = 0,
  green = 0,
}
--set matches[2] to a local variable (not really needed)
local color = matches[2]
--increment the value
Count[color] = Count[color] + 1
Then all your amounts would be stored in the Count table to be referred to like so...
Code: [show] | [select all] lua
echo("I have "..Count.red.." red potions!")

Post Reply