This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
EveryOS's profile picture

What does _G['item']=item do?

Started by EveryOS, 21 March 2016 - 10:00 PM
EveryOS #1
Posted 21 March 2016 - 11:00 PM
I'm curious.
Dragon53535 #2
Posted 22 March 2016 - 02:18 AM
Unless you have a variable in local scope called item, it does absolutely nothing.

Edit: To elaborate, it sets item to the value it was already at.
Edited on 22 March 2016 - 01:18 AM
Bomb Bloke #3
Posted 22 March 2016 - 03:19 AM
_G.item = whatever    -- Sets an item in _G to whatever. Can then be accessed from anywhere.
item = whatever       -- Sets a global to whatever. Can then be accessed from anywhere in the current environment.
local item = whatever -- Sets a local to whatever. Can then be accessed within the current code block, or within nested blocks.

When you check the value of "item", if a local variable with that name exists, that gets used. If not, then if a variable with that name is a global of the current environment, then that gets used. If not, then if _G.item exists, that gets used. Failing all that, you finally get nil.

Usually in Lua, _G is your environment. But in terms of ComputerCraft, each shell instance gets its own environment (but can still access _G), and notably any APIs you load can't access any globals in those custom environment tables (as APIs aren't tied to a specific shell instance). So if you're running multiple shells on a system (eg via multishell tabs) and want to share vars, or want your APIs to be able to access certain variables, you'd manually dump them into _G.

http://lua-users.org/wiki/ScopeTutorial

http://www.lua.org/pil/14.html