Trying to Concatenate two strings into a variable

I’m having trouble understanding how to concatenate two strings and then turn into a variable. The line of code I’m talking about is this:

text("No. of "..self.building.."s owned: "..self.building.."No", 380,320)

self.building is a string “Cursor”. I want join self.building with “No” to read the variable called CursorNo. Is there a way to do this in text or do I need a different function?

Thanks :slight_smile:


a = loadstring(self.building.."No")

I dont have it right, but dont have time to fix it, play with loadstring anyway, it’s what you want

Ok thanks @Ignatz I’ll play around with that!

This the output when I print what you said above. CursorNo should equal ten. Am I using this wrong?

Try this instead


you must put [] when between the ! and the () when you want to display an image (i’ve fixed it in your post).
And you can copy codea output just by touching the line (it is in your pasteboard then, there is no warning about this)

Call me an old fuddy-duddy, but arriving at a variable name by concatenate seems like bad practice to me. Instead of a variable called CursorNo, why not a variable No inside table Cursor? Eg:

    Cursor = {No = "my variable"}
    building = Cursor
    str = "No"

Or have I misunderstood what you’re trying to do?

Yojimbo2000 +1

A handy way to concatenate is use a function like below to make sure all your values are a string before concatenating them :slight_smile:

function concatToString(...)
    local tbl = {...}
    for i,v in ipairs(tbl) do
        tbl[i] = tostring(tbl[i])
    return table.concat(tbl)

-- usage example: (you can pass any number of arguments of any type)

local myString = concatToString("Test ",1," ",2," 3 ",function() end," ",{})


Most of the time that’s not necessary though because Lua has implicit type conversion. If you need a function like that then you’re trying to concat something not supported by implicit conversion, which probably means you should go back to the drawing board. Eg getting a variable name by concat is slow, error prone, and needlessly complex.

It really doesn’t very well when your concatenating, try it :slight_smile:

The function also avoids multiple concats which you would get using the “…” operator :slight_smile:


local str = "concat ".."this ".."together"

-- first becomes "concat this " (or "this together" depending on the order that lua handles this) so the next operation is:

str = "concat this ".."together"

Totally agree on avoiding getting variable names that way, it’s just asking for trouble. Should be one of those solutions reserved for when you have no other option :wink:

Assuming that CursorNo is global, _G[self.building .. "No"] will do what you’re looking for.

Thankyou all,

@Jmv38 I didn’t know that, but that sure is useful!

@yojimbo2000 That’s a great idea! I didn’t even think about using a table.