How do I make a dynamic variable name in Lua?

前端 未结 3 1210
走了就别回头了
走了就别回头了 2020-12-11 18:14

I am new to Lua and am having some difficulties:

I am trying to create dynamic variable names:

local tblAlphabet = {\"a\",\"b\",\"c\",\"d\",\"e\",\"f         


        
相关标签:
3条回答
  • 2020-12-11 18:43

    You can create a table which contains your variables.

    local tblAlphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}
    local vars = {}
    for k, v in pairs(tblAlphabet) do
        vars[v .. "_button"] = ui.newButton()
    end
    

    Then you can access vars via iterators or direct access (vars.a_button).

    0 讨论(0)
  • 2020-12-11 18:53

    The variables you create are first-class values that do not have names.

    You can assign them to variables which have names. Either local variables, or in this case (since you want to do it in a loop), key names in a table (either the globals table, or a table you create).

    You do not need a data table to create your button names, since they follow a simple pattern.

    t = {}
    for b = string.byte('a'), string.byte('z') do
        c = string.char(b)              -- 'a' to 'z'
        t['button'..c] = ui.newButton() -- something like this
    end
    
    0 讨论(0)
  • 2020-12-11 18:59

    it's not clear what you want to do; but if you want to programmatically create lots of global variables, just remember that globals are fields of the _G table:

    _G['anyvar'] = 'something'
    print (anyvar)
    
    0 讨论(0)
提交回复
热议问题