IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

attempt to index global 'XXX' (a nil value)

attempt to index global 'XXX' (a nil value)はスコープの指定がわるいため。

エラーになる場合

> Foo = {
>>   Bar = {[1]="Bar-1", [2]="Bar-2"} 
>> ,[1] = "Foo-1" 
>> ,[2] = "Foo-2"
>>  , bazz = function(v) return Bar[v] end
>> }
> = type(Foo.bazz)
function
> = Foo.bazz(1)
stdin:5: attempt to index global 'Bar' (a nil value)
stack traceback:
    stdin:5: in function <stdin:5>
    (...tail calls...)
    [C]: in ?

Barがみえないので、Foo.Barと指定する。

> Foo = { 
>> Bar = {[1]="Bar-1", [2]="Bar-2"}
>> ,[1] = "Foo-1"
>> ,[2] = "Foo-2"  
>>  , bazz = function(v) return Foo.Bar[v] end
>> }
> = Foo.bazz(1)
Bar-1
>

lua - Attempt to index global 'object' (a nil value) - Stack Overflow