Changing Variable by using variable+string? LUA

Viewed 216

I have a script where I have many variables for different guns. There are

UMP45Ammo = false
UMP45Fov = false

AKMAmmo = false
AKMFov = false

etc I got like 12 guns and more variables

Then I have a global variable called cgun

My problem is when a button is clicked I wanna change the value of selected guns specific property(like ammo to true)

So I tried something like
cgun+Ammo = true and I tried even making new local variable

mgun1 = cgun+Ammo 
mgun1 = true

etc. How can I do this or is it impossible?

2 Answers

It may be better to use objects to describe the guns. Then it's easy to change a gun property of the current gun.

-- gun list
UMP45 = {Ammo = false, Fov = false}
AKMA = {Ammo = false, Fov = false}

cgun = UMP45  -- set current gun
print(cgun.Ammo)

cgun.Ammo = true -- set Ammo of current gun
print(cgun.Ammo)

Yes, it is possible to access global memory using the _G variable. It works, but it's ugly in this case:

_G[cgun.."Ammo"] = 0

Note that if cgun is a reference you have to change it to a string, either using debug.getlocal or using a simple search:

 for k, v in pairs(_G) do if v == cgun then _G[k.."Ammo"] = 0 break end

Again this is not a very good solution. Generally speaking, you don't want to pollute the global space _G with a lot of variables.

Just store a reference to your current gun as Mike suggested.

currentGun = { ammo = 10, name = "AK47" }
Related