Implementing in-game Lua scripting


I am wondering, how would you implement in-game scripting for a game made in Defold? Since Defold is in Lua already I assume it should be easy?

My first thought was that my Defold project could ‘require’ a .lua script file that the user would provide in some outside directory location. But, it seems a defold project can only take scripts from within the project directory structure right? And even if you could do that, would building the project to windows/mac/linux break this?

I am thinking I would have created functions in my player.script that would provide game state info (e.g. distance to target, etc). But what I want is to expose those functions to the user via some kind of api - so that the user can add functionality and tell the player when to do things like fire weapons via scripting.

Any suggestions on how to do this? It seems like it should be easy, but my rudimentary efforts have failed.



You can dynamically run Lua code with loadstring() but it’s very dangerous unless you first process the scripts to remove nasty code.



hmm, with some more searching I found this:

(a lua library for running untrusted lua code) So maybe this library with loadstring() could work.



That does seem like a possible option for you. Please try it and let us know here how it works for you.



ok, so I did get loadstring() to work… I use assert(loadstring(’./test.lua’)) to execute a command in my external file. (e.g. print(‘hello world’)).

But let’s say, I have a player.script on my player GO. And in my player.script, I have defined:
local currently_contacting_ground = true

So let’s say in my test.lua script I want to have a command for my player to jump, if currently_contacting_ground is true.

But, the test.lua script has no access to the currently_contacting_ground… So I haven’t really achieved my goal - I haven’t been able to expose anything about the game state to the external script. Any ideas about that?



You can use messaging to send messages to your player script from the executed script somehow. As long as the script which is doing the loadstring() has a Lua module required in it the executed code should be able to use it too I think.

Broadcast is what I usually use for publish / subscribe so you don’t have to worry about exact script paths.



You can also have a look at Defold Codepad.

1 Like