Patryk
Patryk

Reputation: 24092

How can I access c++ class member function from lua script?

I think the problem I want to solve will an easy one for most of you:) Suppose I have a class Node which has a member function setPosition(float x, float y, float z). I would like to be able to define a variable of class Node in lua and then be able to use setPosition() function also form the Lua. I know that there are issues that Lua is rather for C not C++ and has its issues with C++ classes but I also know that it is achievable.

Upvotes: 1

Views: 1621

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

I'd use Luabind for this. With it you can easily bind C++ classes so they can be created, accessed, and modified in Lua. The code you'd write in C++ might look roughly like this:

module(L) [
    class_<Node>
        .def(constructor<>)
        .def("setPosition", &Node::setPosition)
];

Then you'd be able to say this in Lua:

node = Node()
node:setPosition(x, y, z)

You could also make bindings so that the Lua looks a little more natural and could support things like these:

node1 = Node(x, y, z)
node2 = Node()
node2.position = { x, y, z }

Upvotes: 1

Related Questions