A small module that allows you to call a method only once without the need of making extra variables for it.
The once.lua file should be dropped into an existing project and required by it.
once = require "once"
You can then use once
to create a new once-object with once.new(obj)
, where you pass the object you want to use once with.
Let's assume your object has the function foo
, which prints the first argument. We can then use once like this:
function object:update(dt)
self.once:foo("Hello World!")
end
Only on the first frame will foo be called. You can also call once as function and pass either the name of the method or the method directly as first argument.
function object:update(dt)
self.once("foo", "Hello World!")
self.once(self.foo, "Hello World!")
end
If you want your method to be called again, you can free it by passing the name of the method as first argument.
You can add a second method (f2
) that, in case f
was trapped, will be called.
-- When a is pressed, foo will be freed again and bar will be called.
-- Foo will be called again next frame.
function object:update(dt)
self.once:foo("Hello World!")
if keyPressed("a") then
self.once:free(self.foo, self.bar)
end
end
This library is free software; you can redistribute it and/or modify it under the terms of the MIT license. See LICENSE for details.