Fox
Fox

Reputation: 584

Lua - How to use constants with vars?

I don't really have a clue of lua so sry if this is dumb ^^'

I have a constants(?) like this:

Config.name

It content is "true" or "false". I set this constant-name(or member name?) dynamicly, so it can be for example: Config.george, Config.steve or Config.tim. Now I want to check this constant, but I don't know how the syntax is.

I want something like this:

for _, friend in pairs(friends) do
    if Config.friend.name then
        print("He is checked!")
    end
end

The "friend.name" should be the name of that friend, george for example. How is that done?

Upvotes: 1

Views: 935

Answers (1)

greatwolf
greatwolf

Reputation: 20838

It looks like you're checking whether a given name is set to true in the Config table. Assuming friends is a table of names you want to check against, the code would be:

local friends = { 'george', 'steve', 'tim', } 
-- ...
for _, friend in pairs(friends) do
  if Config[friend] then
    print(friend.." is checked!")
  end
end

Note that ipairs can also work here or just iterate by index:

for i = 1, #friends do
  if Config[ friends[i] ] then
    print(friends[i] .. " is checked!")
  end
end

Upvotes: 2

Related Questions