how to assign lua variable by reference

后端 未结 2 1497
花落未央
花落未央 2020-12-19 09:29

How can I assign a variable by reference in Lua to another one?

For example: want to do equivalent of \"a = b\" where a will then be a pointer to b

Backgr

相关标签:
2条回答
  • 2020-12-19 09:47

    It's true the variables are just names for values. But you can compute variable names, if you are dealing with keys in a table. This means you can use key names to perform your conditional logic.

    myvars = { a=1, b=2, c=3.14 }
    
    function choose(input)
        print(myvars[input])
    end
    
    choose('a')
    choose('b')
    a = 'a'
    choose(a)
    b = a
    choose(b)
    a = 'c'
    choose(a)
    choose(b)
    

    Output:

    1
    2
    1
    1
    3.14
    1
    
    0 讨论(0)
  • 2020-12-19 09:59

    EDIT: regarding your clarifed post and example, there is no such thing as a the type of reference you want in Lua. You want a variable to refer to another variable. In Lua, variables are simply names for values. That's it.

    The following works because b = a leaves both a and b referring to the same table value:

    a = { value = "Testing 1,2,3" }
    b = a
    
    -- b and a now refer to the same table
    print(a.value) -- Testing 1,2,3
    print(b.value) -- Testing 1,2,3
    
    a = { value = "Duck" }
    
    -- a now refers to a different table; b is unaffected
    print(a.value) -- Duck
    print(b.value) -- Testing 1,2,3
    

    You can think of all variable assignments in Lua as by reference.

    This is technically true of tables, functions, coroutines, and strings. It may as well be true of numbers, booleans, and nil, because these are immutable types, so as far as your program is concerned, there's no difference.

    For example:

    t = {}
    b = true
    s = "testing 1,2,3"
    f = function() end
    
    t2 = t -- t2 refers to the same table
    t2.foo = "Donut"
    print(t.foo) -- Donut
    
    s2 = s -- s2 refers to the same string as s
    f2 = f -- f2 refers to the same function as f
    b2 = b -- b2 contains a copy of b's value, but since it's immutable there's no practical difference
    -- so on and so forth --
    

    Short version: this only has practical implications for mutable types, which in Lua is userdata and table. In both cases, assignment is copying a reference, not a value (i.e. not a clone or copy of the object, but a pointer assignment).

    0 讨论(0)
提交回复
热议问题