String Concatenation, Functions, and Class Fields (oh my!)

I am trying to create a function that takes a string provided as a parameter and concatenates it with a string “Cost”. This is a field of the class. So, If bazaar.forSale = “food”, then “food” is passed to Bazaars:buy(what) where what is “food”. The cost of the food is foodCost. When I do the concatenation, and print() it, it looks correct, but the value is nil, rather than the value. I have tried making a local variable and build the string there, (local WHAT = what … “Cost”) but it is still nil. I’m sure I am making some really wrong assumption here, but is what I am trying to do possible? Is this what loadstring would be good at? I hope I have made a little bit of sense, as English is my primary language, not programming.

TextAreas =  class()
function TextAreas:touched(button)
    if button == "yes" then
    bazaar:buy(bazaar.forSale)
end

Bazaars = class()
function Bazaars:init(foodCost, warriorCost, scoutCost, healerCost, beastCost, forSale)
    self.foodCost = 1
    self.warriorCost = math.random(4,8)
    self.scoutCost = math.random(16,24)
    self.healerCost = math.random(17,25)
    self.beastCost = math.random(18,26)
    self.forSale = "food"
end
function Bazaars:buy(what)
    if Tplayers[cP].gold >= self.what .. "Cost" then
        Tplayers[cP].gold = Tplayers[cP].gold - what .. "Cost"
        if what == "food" or what == "warriors" then
            Tplayers[cP].what = Tplayers[cP].what + 1
        else
            Tplayers[cP].what = true
        end
    else -- Out of money
        self.forSale = "closed"
        status.text = statusText[3.9]
        wait = 30
    end
end

Thanks.
Jim

jlslate, :slight_smile:

instead of self.what … “cost” do self[ what … “cost” ]

self.what … “cost” should be equivalent to self[ what ] … “cost”

Thanks! That solved my dilemma perfectly. I just got used to the shortcut method.

It might be easier instead to have a field “costs” like this:

function Bazaars:init()
    self.costs = {
        food = 1, 
        warrior = math.random(4,8),
        scout = math.random(16,24)
        healer = math.random(17,25),
        beast = math.random(18,26)
    }
    self.forSale = "food"
end

function Bazaars:buy(what)
    if Tplayers[cP].gold >= self.costs[what] then
        ... etc ...

It might have been about a month ago when I started this, but I’m afraid it would require quite a re-write at this juncture. :frowning:

Thanks for the thought, though. I might end up rewriting a bunch of it as I get a better idea of how to use Codea.

Jim