简体   繁体   中英

the difference between loadstring and a normal function definition in Lua?

I'm playing with Lua, following the link: https://www.lua.org/pil/8.html . And I got confused a bit...

> i = 100
> local i=3
> f=loadstring("i=i+1")
> print(i)
100
> g=function() i=i+1 end
> print(i)
100
> f()
> print(i)
101
> g()
> print(i)
102

I mean, why neither f nor g use the local i?

You already have an answer for that in one of your previous questions .

> local i=3

Since you are using Lua interpreter in interactive mode, the local i is only visible in the chunk I have quoted above. Hence, both f and g increase global i as they don't see local i from the chunk quoted.

Consider writing your Lua code to a file and then executing them via eg: lua file.lua .

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