Implementing in-game Lua scripting

#1

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.

0 Likes

#2

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

0 Likes

#3

hmm, with some more searching I found this: https://github.com/kikito/sandbox.lua

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

2 Likes

#4

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

0 Likes

#5

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?

0 Likes

#6

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.

0 Likes

#7

You can also have a look at Defold Codepad.

1 Like