Log In  

I wonder what is the scope of a variable if I define it outside of a function as "local" in Pico. So is it local to some kind of root scope within Pico? Is it local to the tab? Seems to me that it"s still possible to use this "local" variable everywhere then, right, since ever other scope is a child to this root scope?

local x=5 -- what means local here?
y=6 -- global scope
P#138839 2023-12-18 14:37

one difference I found is that if I have a global variable it will be available everywhere, and every time, while when working with "root locals" I have to make sure that those variables are defined before a function using it, otherwise Pico will look into the global scope to find that variable.

P#138844 2023-12-18 15:30

I think you got it!

tabs don’t exist for the lua runtime, they are a purely cosmetic thing that the pico8 code editor uses to separate parts of the code, but they don’t create separate files or chunks (what lua calls modules).

if you look at a P8 file in a text editor, you can see that the tab separations are just ascii scissors -->8 and actually interpreted as comments by lua.

local x in a function (or a do) block makes the variable local to the block, and at the top-level it makes it local to the chunk (the whole file), meaning it works mostly just like a global. but try this:

function test()
 print(a)
 print(b)
end

a=12
local b=13

test()
P#138845 2023-12-18 15:34 ( Edited 2023-12-18 15:37)

thanks. ok, yeah then I think I got the difference. in your example test() will output

12
nil

right?

I wonder if there is any other difference. I remember reading somewhere that using local scope is a little faster than global scope but if this transfers to Pico, I am not sure. Something along the line of that accessing globals is always a table lookup while locals are stored in a c array within the lua virtual machine.

P#138847 2023-12-18 15:52

[Please log in to post a comment]