enviornment of child function created by loadstring lua

时间:2015-10-30 22:27:59

标签: lua

Why does the calls to f() and g() give different results? They both inherit environment from the parent function, run, but f() does not change j.

myString = "print('i,j in myString before setting', i, j);\
            i = 'fi'; j ='fj'\
            print('i,j in myString after setting', i,j)"
j = 1
print('j initial value', j)

function run(i)
    i = 'i'
    print('i initial value', i)
    f = loadstring(myString)
    if not f then
        print('load failed')
    else
        print('=== load ok, now execute')
        f()
        print('=== end of execution')
    end
    print('i,j after f()', i,j)

    g = function()
        i = 'gi'; j = 'gj'
    end
    g()
    print('i,j after g()', i,j)
end

run(i)

Results:

j initial value   1
i initial value   i
=== load ok, now execute
i,j in myString before setting   nil   1
i,j in myString after setting fi fj
=== end of execution
i,j after f()  i  fj
i,j after g()  gi gj

Note the different values of i after f() and g() calls.

1 个答案:

答案 0 :(得分:2)

You are referring to two separate i variables.

When you call f() it's accessing a global i, whereas you are accessing run's argument i in g().