Reputation: 145
I have looked this question up so many times that I am convinced I am missing a huge piece of the puzzle when it comes to integrating LUA into my C++ Game Engine. What I want to do is run my game engine, then while its running I would like to click on my ui and click "add script" and then run the script. That part is easy enough to do but what I DON'T get is how a script that seemingly gets ran in place with lua_dofile could have code that gets mouse input or moves the character based on input. I don't see anyway to do this effectively. Am I supposed to allow the LUA state to be created and destroyed every frame or do I make the script fire every frame? In an application like this:
void init();
void update();
void render();
void end();
How would I use LUA to control the movement of an entity.
Lets say I set up the lua state so that you can write lua code like this:
entity1 = Entity.new()
entity1:setPosition(4,5)
How would I give the script some input from mouse to move the entity to the mouse position?
My overarching question is what is the best way to have a script control my entities in a way that if I supply the Lua State the ability to move my entities, then a scripter could write a "game" (i.e. a interactive runtime application)
Upvotes: 2
Views: 1066
Reputation: 72312
Essentially the Lua scripts define functions to be called at each event. So the host C++ loads the scripts and then enters its main loop and calling back Lua.
See how LÖVE does it.
Upvotes: 0
Reputation: 48572
To give a concrete example, suppose you wanted to teleport a ball to the player whenever they click the mouse. Here's what you could write to do that in Lua:
local function clickHandler(event)
local x, y, z = event.player:getCoords()
local ball = event.world:getBall()
ball:teleportTo(x, y, z)
end
game.registerEventHandler('click', clickHandler)
To make that example actually work in your engine, here's what you'd need to do:
registerEventHandler
function that saves the given callback somewhere C can access itgetCoords
function that returns the coordinates of a given playergetBall
function that gets a ball in your gameworldteleportTo
method that teleports an entity to a given locationclick
event handlers that you saved, with an event
object containing the player and the gameworldAnd as for this question in particular:
Am I supposed to allow the LUA state to be created and destroyed every frame or do I make the script fire every frame?
No. You create a lua_State
when your game starts, load the scripts in it, and then just keep using that state to call the event handlers.
Upvotes: 1