简体   繁体   中英

enviornment of child function created by loadstring 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.

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM