Last active
December 22, 2015 14:59
-
-
Save Bradshaw/6489519 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function thing() | |
local t = {} | |
--[[ Local to the function "thing()" | |
but we're going to return it so it becomes directly accessible. | |
We're making this local ONLY to avoid conflicts with any global | |
variable with the same name. | |
--]] | |
local hp = 100 | |
--[[ Local to the function "thing()" | |
We're not returning it, so it can only be touched by something | |
else also local to "thing()" | |
How about we write some functions that we store in t ? | |
--]] | |
-- The followong functions are legal to write because hp is in their context | |
t.hit = function() | |
hp = math.max(0,hp - 1) | |
end | |
t.remains = function() | |
return "lua: You have "..hp.." left..." | |
end | |
t.alive = function() | |
return hp>0 | |
end | |
return t -- We return t | |
end | |
dude = thing() -- "thing()" returns a table, which contains some functions | |
--[[ When we call those functions, they access stuff that was accessible | |
to them *when they were defined* | |
So while hp does not exist in THIS context, it exists in THEIR context | |
--]] | |
while dude.alive() do | |
print(dude.remains()) | |
dude.hit() | |
end | |
--[[ Note, we can't do dude.hp since hp isn't stored in dude. | |
It isn't stored in ANYTHING besides a variable named hp that | |
existed in a context a long time ago, but as long as other things | |
that were in its context still exist, he still remains. | |
--]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment