Pergunta

First, let me explain my setup. I have 2 lua files: one is the main program to run and the other is a configuration file. In the main program, it runs through the configuration file once and loads all the tables to memory. If I want to add a new configuration, I don't want to have to reprogram the main program, I want to be able to just add a new table in the configuration file.

The main program:

-- Read config
dofile("config.lua")

-- Ask for ID
inputtedID = io.read()
-- Check if it exists
if string.format("%s[enabled]", inputtedID) then
    -- If table exists and enabled key is set to true
    print('"' .. inputtedID .. '" does exist!')
else
    -- If the table doesn't exist or the key is false
    print('"' .. inputtedID .. '" does not exist')
end

The configuration file:

Public = {
enabled = true,
directory = "whatever"
}
Snapshot = {
enabled = true,
directory = "something"
}
-- So forth and so on

Each table will have the same keys to be read, but the one we need to focus on is the enabled key. Which brings us to this...

I want it to take the user input, check to see if there is a table that matches the user input, and check if the enabled key value in that table is true. If the table does not exist or the value is false, then just run a different set of code asking to retry.

And to be specific where I'm getting stuck, it's whenever I try using a variable when referring to or working with a table. I don't know how it can be done, nor do I know how it's supposed to be done.

Foi útil?

Solução

All global variables are members of the global table, called _G, which you can then index by the name of your variable:

-- Read config
dofile("config.lua")

-- Ask for ID
inputtedID = io.read()

-- Check if it exists
if _G[inputtedID] and _G[inputtedID].enabled then
    -- If table exists and enabled key is set to true
    print('"' .. inputtedID .. '" does exist!')
else
    -- If the table doesn't exist or the key is false
    print('"' .. inputtedID .. '" does not exist')
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top