Advertisement

LuaBind properties within Lua...

Started by December 15, 2010 03:56 PM
1 comment, last by Nanoha 13 years, 3 months ago
LuaBind allows you to bind getter/setter functions to a "property" that can be assigned and accessed as a value.

class_<Scene>("Scene")    .def(constructor<Renderer*>())    .property("rootSceneNode", &Scene::getRootSceneNode),


In Lua...

scene = Scene(renderer)scene.rootSceneNode = SceneNode()scene.rootSceneNode : translate(Vector3(1, 0, 0))


My question is this: How can I implement these "properties" where getter/setter functions are called on assignment and access purely in Lua?

class 'Test'function Test : __init(value)    self.value = valueendfunction Test : getLength()    return # self.valueend// How do I create a length "property" which calls getLength when I do this.test = Test({1, 2, 3, 4})print(test.length)
For any future Googlers out there, like myself... it turns out you can create Luabind properties from Lua, and while the functionality is undocumented (at least as of version .91), here's how it works:


class 'Test'

-- declare getters and setters first
function Test : getLength()
return # self.value
end

function Test : setLength(newLength)
for i = self.length, newLength do
table.insert(self.value, false)
end
end


function Test : __init(value)
self.value = value
-- version with getter and setter
--self.length = property( Test.getLength, Test.setLength )
-- just getter
self.length = property( Test.getLength )
end


test = Test({1, 2, 3, 4})
print(test.length)
Advertisement
I came across this thread after some gooogling, so for other future googlers I also like to add:

I define and create one of my classes in c++ and then expose it to lua (Generic Entity class). I wanted to make it a bit more specific in lua (its a player) by adding some helper functions/properties. I found I couldn't use the "self" table in lua, instead I had to do it like this:

Overkill.player = e; -- e is passed in to this (it's in a fucntion) - "e" is an "Entity" object
Overkill.player.GetHealth =
function(s) -- notice the s
local h = s:GetComponentByType(Overkill.HealthComponent.componentType);
if not h then return 0 end
return h.currentHealth;
end
Overkill.player.SetHealth =
function(s, health) -- notice the s
local h = s:GetComponentByType(Overkill.HealthComponent.componentType);
if not h then return end
h.currentHealth = health;
end


You'll notice the Get/Set functions both take a variable (s, though it can be anything), the object gets passed in as that parameter when the property is used. It works like "self". I can use the property as usual then:

local health = Overkill.player.health;
Overkill.player.health = 15;

Interested in Fractals? Check out my App, Fractal Scout, free on the Google Play store.

This topic is closed to new replies.

Advertisement