简体   繁体   中英

Using C++ w/ Lua in a runtime environment

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" (ie a interactive runtime application)

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:

  • Create a registerEventHandler function that saves the given callback somewhere C can access it
  • Create a getCoords function that returns the coordinates of a given player
  • Create a getBall function that gets a ball in your gameworld
  • Create a teleportTo method that teleports an entity to a given location
  • Whenever a player clicks the mouse, run all click event handlers that you saved, with an event object containing the player and the gameworld

And 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM