|
| 28 Mar 2010 07:14 PM |
I tried to make a script using a local variable: function blah() local x = game.Players.merlin11188 end
function kill() x.Character.Humanoid.Health = 0 end
--service lines-- Those two things were in the same script. This didn't work, but only because of the "local" part. (I just made this up on the spot, so there are probably errors.)
So, I also tried: function blah() _G.x = game.Players.merlin11188 end
function kill() x.Character.Humanoid.Health = 0 end
--service lines--
That one worked, although I don't know why the local one didn't. If you would please enlighten me. Yes, kill() and blah() are in the same script. |
|
|
| Report Abuse |
|
|
|
| 28 Mar 2010 07:21 PM |
local variables use environments or scope, rather than being availible to the whole script. The block a local variable is declared in, will be the place where it is in scope, and any blocks inside that block will have access to that variable. But, any blocks outside that block will not be able to access the variable because it has fallen out of scope.
ie.
do local x = 1 --in scope do print(x) --in scope end end print(x) --not in scope do print(x) --not in scope end |
|
|
| Report Abuse |
|
|
GoldenUrg
|
  |
| Joined: 23 Aug 2009 |
| Total Posts: 6428 |
|
|
| 28 Mar 2010 07:52 PM |
More specific to you're example:
-- local variable -- available to all functions in this "scope" local x function blah() x = game.Players.merlin11188 end
function kill() x.Character.Humanoid.Health = 0 end
Like b3ttur suggested, you can create scopes with do ... end, repeat ... until or function() ... end
-- "global" variable in local environment -- available to all functions in the script function blah() x = game.Players.merlin11188 end
function kill() -- assuming no local x x.Character.Humanoid.Health = 0 end
-- "global" variable in global (_G) environment -- available to all scripts running on this copy of Roblox function blah() _G.x = game.Players.merlin11188 end
function kill() -- assuming no x local or global in local environment x.Character.Humanoid.Health = 0 end
|
|
|
| Report Abuse |
|
|
|
| 28 Mar 2010 08:37 PM |
| Oh I see! Because x was created inside the function, when the function ends, the scope ends. And so x is nil because it's outside of it's scope. Thanks a lot! |
|
|
| Report Abuse |
|
|
|
| 28 Mar 2010 08:40 PM |
| Umm, wow. Most of the time when I explain this, people are like "lolwut? this is useless, I'm never going to use local again!", I'm actually suprised you understood most of that(I tend to explain things horribly becuase I hate over-simplifying)... |
|
|
| Report Abuse |
|
|
|
| 28 Mar 2010 08:40 PM |
| However, can you set a variable as instance outside of a function? |
|
|
| Report Abuse |
|
|
| |
|
|
| 28 Mar 2010 08:44 PM |
| Thank you very much :D. Pleasure doing business with you. |
|
|
| Report Abuse |
|
|