Thats Amazing! (Closure)
Posted: Sat Nov 16, 2013 7:13 pm
My God, Lua where have you been all my life!
So any of you guys know some cool ways I could use closure in a game?
or some simple examples would be awesome \(^m^)/
Code: Select all
local function get()
--code
end
local function set(new_v)
--code
end
Code: Select all
-- myfile.lua
local SOMETHING_COOL = 'cool'
function test()
print(SOMETHING_COOL)
SOMETHING_COOL = SOMETHING_COOL:rep(2)
end
-- anotherfile.lua
require 'myfile'
test() -- cool
test() -- coolcool
It sounds like I may have confused you a bit so I'll explain more.Ekamu wrote:o.k..
I get confused with closure in tail calls. would the particle system use closure if for example it was to run itself over and over for a certain time, and each time calling upvalues from within itself or is it only closure when upvalues are from somewhere completely different like another function...
so we wont use closure with recursion but its OK with normal tail calls and general code right?
Code: Select all
function createClosures()
local t = {}
for i = 1, 10 do
t[#t+1] = function() return i end
end
return t
end
Code: Select all
function createParticle()
local self, x, y = {}, 0, 0
function self:draw()
-- drawing code here
end
function self:update(dt)
-- updating code here
end
return self
end
particles = {}
for i = 1, 10000 do particles[i] = createParticle() end
Here I made 3 tables, 20002 variables, 3 functions, and either 1 or 3 closures (I'm not sure if lua 5.1 shares that lexical environment, but I know lua 5.2 does). This code tends to be a bit more messy, so you only use this style for things where performance is crucial.particles = { x={}, y={}, N=0 }
function particles.create()
particles.N = particles.N + 1
particles.x[particles.N] = 0
particles.y[particles.N] = 0
end
function particles.draw()
for i = 1, particles.N do
-- drawing code
end
end
function particles.update(dt)
for i = 1, particles.N do
-- updating code
end
end
for i = 1, 10000 do particles.create() end