Lua multiple assignment with tables

前端 未结 4 2020
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 08:36

This code:

function foo()
    return 1, 2, 3
end

bar = {}

bar = {a, b, c = foo()}

produces:

bar.a = nil
bar.b = nil
bar.c         


        
4条回答
  •  天命终不由人
    2021-01-12 09:05

    bar = {}
    local abc = foo()
    bar.a, bar.b, bar.c = abc, abc, abc
    

    Simply bar.a, bar.b, bar.c = foo() will only set bar.a to foo(), the other two will be set to nil because they get set to the second and third values respectively, and you've only given one value.

提交回复
热议问题