custom lua godot engine module

Overview

Godot Lua Module

Table of contents:

About

This is a Godot engine module that adds lua support via GDScript. Importantly this is NOT meant to be a replacment for GDScript. The main purpose of this module is to add runtime execution of code for tasks such as modding or in game scripting.

While the original purpose of this module was for my own use I understand more may find it useful. If a feature is missing that you would like to see feel free to create a Feature Request or submit a PR

By default lua executes on its own detached thread. If thread saftey is required you can either use mutex locks or disable threading.

To use you can either Compile from source or if you are on windows or linux you can download one of the pre built binarays from th releas page.

Default lua libs loaded

  • base
  • math
  • string
  • table

Features

  • Run lua directly from a string or a text file.
  • Push any Variant as a global.
  • Expose GDScript functions to lua with a return value and up to 5 arguments.
  • By default the lua print function is set to print to the GDEditor console. This can be changed by exposing your own print function as it will overwrite the existing one.

TODO

  • Add support to kill individual lua threads.
  • Add option to load specific lua librarys.

Compiling

Please note this module was written for Godot Version 3.2.3

  • Start by cloning the Godot 3.2.3 source with this command git clone https://github.com/godotengine/godot -b 3.2.3-stable

  • Next clone this repository into the module folder inside the Godot source code.

  • Now you can follow the Godot build instructions on their site.

Examples

Running lua from a string:

extends Node2D

onready var lua = Lua.new()

func _ready():
	# The third option is to pass a error call back function. passing String() like this will disregard it
	lua.doString(self, "for i=1,10,1 do print('Hello lua!') end", String())

Running lua from a file:

extends Node2D

onready var lua = Lua.new()

func _ready():
	lua.doFile(self, "user://luaFile.lua", String())

Pushing a Variant as a global:

extends Node2D

onready var lua = Lua.new()
var test = "Hello lua!"

func _ready():
	lua.pushVariant(test, "str")
	lua.doString(self, "print(str)", String())

Exposing a GDScript function to lua:

extends Node2D

onready var lua = Lua.new()

func luaAdd(a, b):
	return a + b

func _ready():
	lua.exposeFunction(self, "luaAdd", "add")
	lua.doString(self, "print(add(2, 4))", String())

Capturing lua errors:

extends Node2D

onready var lua = Lua.new()

func luaCallBack(err):
	print(err)

func _ready():
	lua.doString(self, "print(This wont work)", "luaCallBack")

Disable threading:

extends Node2D

onready var lua = Lua.new()


func _ready():
	lua.setThreaded(false)
	lua.doString(self, "while true do print("The entire game will freeze") end", String())

Kill all lua threads:

extends Node2D

onready var lua = Lua.new()


func _ready():
	lua.doString(self, "while true do pass end", String())
	lua.killAll()

Contributing And Feature Requests

All contributions are welcome, if you would like to contribute submit a PR.
Additionally if you do not have the time and or the knowledge you can create a Feature Request

Comments
  • Error executing threaded code right after creating Lua object

    Error executing threaded code right after creating Lua object

    The following script doesn't works. It freezes the program and closes shortly after. No message is shown in console.

    func _ready():
    	var lua = Lua.new()
    	lua.doString("for i=1,10,1 do print('Hello lua!') end")
    

    Strangely, this works

    onready var lua = Lua.new()
    func _ready():
    	lua.doString("for i=1,10,1 do print('Hello lua!') end")
    

    This works

    func _ready():
    	var lua = Lua.new()
            lua.setThreaded(false)
    	lua.doString("for i=1,10,1 do print('Hello lua!') end")
    

    Waiting a single frame doesn't freeze the program, but throwns an error message

    func _ready():
    	var lua = Lua.new()
    	yield( get_tree() , "physics_frame" )
    	lua.doString("for i=1,10,1 do print('Hello lua!') end")
    

    error: [string "for i=1,10,1 do print('Hello lua!') end"]:1: syntax error near 'i'

    I think maybe running a separated thread can be tricky. We could use the godot builtin thread model to run Lua and deprecate this module's own thread model... still gotta check if it works properly

    bug 
    opened by rilpires 9
  • Error building on Windows 10

    Error building on Windows 10

    I've cloned this repo under modules/ folder of a 3.2.3-stable Godot Repo and then started scons simply with "scons". Apparently everything compiled, this error goes at the last step (linking final executable)

    scons: Reading SConscript files ... Automatically detected platform: windows Configuring for Windows: target=debug, bits=default Found MSVC compiler: amd64 Compiled program architecture will be a 64 bit executable (forcing bits=64). YASM is necessary for WebM SIMD optimizations. WebM SIMD optimizations are disabled. Check if your CPU architecture, CPU bits or platform are supported! Checking for C header file mntent.h... (cached) no scons: done reading SConscript files. scons: Building targets ... [Initial build] Linking Program ==> bin\godot.windows.tools.64.exe LINK : fatal error LNK1181: não foi possível abrir o arquivo de entrada 'liblua.windows.tools.64.lib'( Translating: Couldn't open input file 'liblua.windows.tools.64.lib') scons: *** [bin\godot.windows.tools.64.exe] Error 1181 scons: building terminated because of errors.

    I'm not familiar with windows linkage, but I guess scons should had accepted luasrc/libs/windows/liblua.a but it didn't?

    bug 
    opened by rilpires 8
  • Can't find Lua module on exported build but it can on editor

    Can't find Lua module on exported build but it can on editor

    I can run Lua code on editor side however on builded windows or html game couldn't find lua. I just export via Project>Export...>Windows Desktop

    image

    I think it is not about my lua code but I will share anyways

    
    onready var lua = Lua.new()
    
    func luaAdd(a, b):
    	Debug.put_log(str(a+b)+" luadan çalıştı")
    	return a + b
    
    func _ready():
    	lua.exposeFunction(self, "luaAdd", "add")
    	lua.doString(self,"print(add(2, 4))","luaCallBack")
    
    func luaCallBack(err):
    	print(err)```
    
    opened by cenullum 7
  • Provide a way to build Lua from source using SCons

    Provide a way to build Lua from source using SCons

    Is your feature request related to a problem? Please describe. I've tried to compile the module on Windows using MSVC compiler, but I'm getting link errors.

    Describe the solution you'd like I suggest that the module provides thirdparty/ Lua source so that the module can be seamlessly compiled for all platforms (including export templates). Currently, this repository provides pre-built libraries which are not guaranteed to work in the future.

    Describe alternatives you've considered I've tried to resolve this myself with:

    #!/usr/bin/env python
    
    Import('env')
    env_lua = env.Clone()
    
    env_lua.Append(CPPPATH=["luasrc/include"])
    
    if env['platform'] == "x11":
        env_lua.Append(LIBPATH=['luasrc/libs/linux'])
    elif env['platform'] == "windows":
        env_lua.Append(LIBPATH=['luasrc/libs/windows'])
    elif env['platform'] == "osx":
        env_lua.Append(LIBPATH=['luasrc/libs/macos'])
    
    if not env.msvc:
        env_lua.Append(LIBS=['liblua'])
    else:
        env_lua.Append(LINKFLAGS=['liblua.lib'])
    
    env_lua.add_source_files(env.modules_sources, "*.cpp") #this will add all the cpp files
    

    But I still get link errors on Windows. Also notice that I've removed absolute path referencing #modules/lua, because it won't work with custom_modules built option either.

    Additional context I do not personally need Lua support at the moment, but I've added this module to https://github.com/goostengine/godot-modules as a git submodule for people to try out, but had to disable it for now. Thanks for sharing!

    opened by Xrayez 7
  • Can't change value while doing

    Can't change value while doing "while loop"

    Test.zip

    In the project I was expecting value will be 0 after pressing F9 which runs trigger function in lua. I also got this error

    test2.lua file:

    
    value=1
    
    function trigger()
       Log("Old value "..value)
       value=0
       Log(value)
    end
    
    while true do 
       value=value+1
    end
    

    image

    opened by cenullum 6
  • Any way to pass an array to lua and back?

    Any way to pass an array to lua and back?

    I want to send a PackedByteArray to lua and have it work with it. Is there any way to do this? Also will luajit ever be supported, or is there a way to add it myself? (sorry if this has been asked already) Thanks a lot for this module! :D

    opened by kicknbrit 5
  •  call_function can't return value

    call_function can't return value

    Is your feature request related to a problem? Please describe. I think call_function can't return values yet.

    Describe the solution you'd like

    if(lua.lua_function_exists("LuaFunctionName") ):
         var value = lua.call_function( "LuaFunctionName",[])
    print(value)
    
    
    function LuaFunctionName()
         return "Hello from lua"
    end
    
    feature request 
    opened by cenullum 5
  • cant send some letter from lua to godot

    cant send some letter from lua to godot

    image

    letters here: ııığşüçö and somehow lowercase letter of " I " turns to number one

    log function is just exposed func to print to console and in game label

    opened by cenullum 4
  • Invalid parametre type on do_string

    Invalid parametre type on do_string

    my code on editor run as expectly, its prints 6 on console but on exported I got this error image

    my code

    
    onready var lua = Lua.new()
    
    func luaAdd(a, b):
    	return a + b
    
    func _ready():
    	lua.exposeFunction(self, "luaAdd", "add")
    	lua.doString(self,"print(add(2, 4))","luaCallBack")
    
    func luaCallBack(err):
    	print(err)
    

    I think liblua in modules\lua\luasrc\libs\windows is old as first init of the repository because it expects string from me like in README.md examples but in editor I had to add self and callback parametres because of warnings. image

    image

    First I thought I made custom export template wrongly however error that say ""lua" isn't declared in the current scope" is gone. and while compiling I saw the lua.cpp image

    opened by cenullum 4
  • Optional protected call for callFunction & fixing iterate over table

    Optional protected call for callFunction & fixing iterate over table

    • This PR solves a problem with Lua::getVariant(int index). When passing a relative index (index<0), the proper way to iterate with lua_next() is indeed using index-1, but when index>0, this should remain only index. This was crashing my project.

    • Also, it gives a proper way to call lua functions from GDScript. Now we could check beforehand if the function actually exists, and we can optionally set it as a protected call. The arguments order were moved. Before, the first parameter Object* doesn't had any utility. I propose to use this same pattern of the same last 3 optional parameters ( bool protected_call , Object* callback_caller , String callback ) in doFile and doString as well, what do you think? To call functions outside protected mode could maybe be more performant, useful when targeting release.

    opened by rilpires 4
  • Problem with await functions.

    Problem with await functions.

    When I call GDScript from under Lua, it (Lua) does not wait for the return of parameters from the function (GDScript), but continues to go further through the code.

    Lua: Снимок экрана 2022-07-12 в 20 46 31

    get_pos() return string (x + " " + y) without using "await". up() - move_up()

    GDScript: Снимок экрана 2022-07-12 в 20 47 27

    Output: Снимок экрана 2022-07-12 в 20 46 53

    opened by sannelo 3
  • V1.1-stae release only has Linux builds

    V1.1-stae release only has Linux builds

    For some reason the v1.1-stavle release only has a limit build. We want editor, export templates and debug export templates for windows, Mac, Linux and web.

    opened by Trey2k 0
  • High memory usage using 'push_variant' to send an array to lua

    High memory usage using 'push_variant' to send an array to lua

    So after some investigation, I found pushing a 7MB PackedByteArray to lua takes up about 8 GB of memory on my machine.

    I allocated the same size array in lua (zerobranestudio) and it took only around 141 MB.

    Here is the code I am using:

    func _ready():
        
        lua = Lua.new()
        
        var buffer = PackedByteArray()
        buffer.resize(7000000)
        buffer.fill(0)
        buffer[77] = 55
        
        lua.push_variant(buffer, "buffer")
        lua.do_string("print(buffer[78])")
        
        
        
        pass
    
    bug 
    opened by kicknbrit 4
  • can't resume a sub-environment

    can't resume a sub-environment

    to preface, sorry about all the issues 😅 i'm trying to put together a game extensively using lua but these issues are very problematic (except the pull_variant one which i've learned to work around fortunately) this one's pretty self-explanatory, if I load a string into a thread reading

    _ENV = game
    print(9000)
    wait_timer(2.0)
    print(2000)
    

    it never prints 2000, only 9000 (i've tried a myriad of different ways, including just calling yield, waiting in gdscript, then resuming the thread. nothing) all relevant functions are exposed to the table/environment of course.

    evidently, execution does stop, so i think it's an issue with LuaThread.resume? i'd guess it's only resuming execution of the global environment. i think that some method of assigning a thread an environment from GDScript would be ideal and circumvent this issue, but there's probably some better way... idk (there's also no equivalent of push_variant/pull_variant for a sub-environment but that's not a big deal just requires a bit of extra code haha)

    bug 
    opened by BestestHD 0
  • pull_variant is broken

    pull_variant is broken

    (built from godot commit ae5668f)

    pull_variant is always LuaError with error type 2 (generic runtime?)

    here's my test code (sorry it's a little messy from me trying different things )

    	lua.push_variant(save.mission, 'MissionVariables')
    	
    	for key in save.mission.Dict:
    		print(key)
    		lua.do_string("%s = MissionVariables.Dict.%s"%[key,key])
    	
    	thread.load_string("print(Wow) Wow = 100 print(Wow) print(Bruh) function Wow() print(99999) end")
    	thread.resume()
    	
    	await get_tree().create_timer(0.5).timeout
    	
    	lua.do_string("function penis(num) print(num) return 200 end")
    	var penis = lua.pull_variant("penis")
    #	penis = penis as Callable IMPOSSIBLE BECAUSE IT'S AN OBJECT ??
    	print(penis)
    #	var num = penis.call()
    #	print(num)
    	
    	for key in save.mission.Dict:
    		print(key)
    		print(lua.function_exists("Wow"))
    		var variant = lua.pull_variant("Wow")
    		print(variant)
    		print(typeof(variant))
    		save.mission.Dict[key] = variant
    

    and the console output...

    Wow
    Bruh
    50
    100
    69
    [LuaError:-9223372008115403638]
    Wow
    true
    [LuaError:-9223372008098626419]
    21
    Bruh
    true
    [LuaError:-9223372008081849191]
    21
    

    trying to save to a resource (my purpose here) nets this

    [sub_resource type="Resource" id="Resource_5f7ft"]
    script = SubResource("GDScript_v8376")
    Dict = {
    "Bruh": Object(LuaError,"type":2,"msg":"unkown lua type '8' in Lua::getVariant","script":null)
    ,
    "Wow": Object(LuaError,"type":2,"msg":"unkown lua type '8' in Lua::getVariant","script":null)
    
    }
    

    if that helps. maybe something with godot broke it recently?

    bug 
    opened by BestestHD 1
  • can't hold resource?!?!?!?

    can't hold resource?!?!?!?

    pretty big issue i've been running into, it's seemingly impossible to load resources. i print the resource and godot just says [Object:null] here's my sample code

    local bgImg
    bgImg = load_texture("res://gfx/tex/bg/tex_bg_terminal_room.png")
    print(bgImg)
    

    load_texture returns a Texture2D, though no resource i've tried works. i haven't tried custom resource yet but that would be seriously damning, for the texture example i can just write a function that returns a sprite and loads the texture from the path onto the TextureRect's texture property but that isn't always an option for some of my game's resources.

    please tell me if it works on your end, for all i know it's just because my build of godot 4 is a little out of date 😅 (waiting until a few specifics PRs are merged...)

    bug 
    opened by BestestHD 2
  • Inheritance bug

    Inheritance bug

    Currently there is a bug when calling a method on a GD class from lua that overrides one of the parents methods. The parents method ends up being called.

    bug 
    opened by Trey2k 1
Releases(v1.1-stable)
Owner
Trey Moller
Someone who likes to think they can code.
Trey Moller
Lua for Plan 9 space

lu9 -- Lua for Plan 9 space lu9 is an umbrella project providing a native Plan 9 port of the Lua library and several other libraries and programs buil

kvik 20 Dec 24, 2022
Disassembler for compiled Lua scripts

Luad English | Русский Luad - Disassembler for compiled Lua scripts. At the moment the program is in development (v0.12-pre-alpha). Supported compiler

Vitaliy Vorobets 12 Oct 20, 2022
a lua extend library

colib 这是一个Lua扩展库,提供了一些常用的扩展功能,该库还在不断完善中。。。 功能列表 已提供的模块有: rtl模块: 提供基础的面向对象实现。 dbg模块: 扩展的traceback函数,可以打印每一调用层级的变量值。 打印Lua对象为字符串形式。 高精度时钟 list对象: 数组对象,接

colin 39 Dec 17, 2022
CMake precompiled header support via custom PCH compiler extension

CMake precompiled header support via custom PCH compiler extension

Adam Strzelecki 102 Dec 9, 2022
curl cmake module libcurl build with msvc x86

curl-msvc Infomation curl cmake module libcurl build with MSVC10.0 arch (x86 | i386) source from https://github.com/curl/curl tags: curl-7_79_1 Usage

Jason Payne 0 May 16, 2022
CMake module to enable code coverage easily and generate coverage reports with CMake targets.

CMake-codecov CMake module to enable code coverage easily and generate coverage reports with CMake targets. Include into your project To use Findcodec

HPC 82 Nov 30, 2022
unmaintained - CMake module to activate certain C++ standard, feature checks and appropriate automated workarounds - basically an improved version of cmake-compile-features

Compatibility This library provides an advanced target_compile_features() and write_compiler_detection_header(). The problem with those is that they a

Jonathan Müller 74 Dec 26, 2022
CMake module for downloading an external project's source at configure time

DownloadProject Platform Build status Linux Mac OSX Windows (VS2015) This repository contains a generalized implementation for downloading an external

Crascit Pty Ltd 433 Dec 16, 2022
CMake module to speed up builds.

cotire Cotire (compile time reducer) is a CMake module that speeds up the build process of CMake based build systems by fully automating techniques as

Sascha Kratky 1.3k Dec 26, 2022
CMake module for building IDL files with MIDL and generating CLR DLL using Tlbimp

FindIDL CMake module for building IDL files with MIDL and generating CLR DLL using Tlbimp. Introduction Requirements Usage find_package() add_idl() ad

Apriorit Inc. 17 Dec 7, 2022
CMake module for building Windows Installer packages with WiX toolset

FindWiX CMake module for building Windows Installer packages with WiX toolset Introduction Requirements Usage find_package() wix_add_project() WiX com

Apriorit Inc. 11 Aug 5, 2022
CMake find module for Intel Threading Building Blocks

FindTBB Module FindTBB is a CMake find package module for Intel® Threading Building Blocks (TBB). Usage The signature of the TBB find module in CMake

Justus Calvin 84 Dec 3, 2022
[CMake] [BSD-2] CMake module to find ICU

FindICU.cmake A CMake module to find International Components for Unicode (ICU) Library Note that CMake, since its version 3.7.0, includes a FindICU m

julp 29 Nov 2, 2022
CMake module for Mathematica.

FindMathematica FindMathematica is a CMake module that tries to find a Wolfram Language installation and provides CMake functions for its C/C++ interf

Sascha Kratky 51 Dec 14, 2022
A versatile script engine abstraction layer.

ScriptX A versatile script engine abstraction layer ScriptX is a script engine abstraction layer. A variety of script engines are encapsulated on the

Tencent 382 Dec 22, 2022
Godot module to use ROS2 within Godot

godot_ros This repo is a Godot Module meant to connect Robotic Operating System 2 (ROS2) and the Godot Game Engine. Quick Start Make sure to have both

Evan Flynn 32 Dec 27, 2022
Godot-steam-api - Godot Steam integration using GDNative.

Godot-Steam-API Godot Steam integration without rebuilding Godot. Supports ?? Windows, ?? Linux & ?? MacOS (x86_x64/arm64). Getting Started Download t

Sam Murray 326 Dec 29, 2022
This API uses both composition and inheritance to provide a generic way to set up a custom server with a custom communication protocol and custom middlewares

Ziapi Summary Introduction Installation Introduction This API uses both composition and inheritance to provide a generic way to set up a custom server

Aurélien Boch 8 Apr 22, 2022
Godot Engine – Multi-platform 2D and 3D game engine

Godot Engine 2D and 3D cross-platform game engine Godot Engine is a feature-packed, cross-platform game engine to create 2D and 3D games from a unifie

Godot Engine 56.7k Jan 9, 2023
A module for Godot 3.x that makes it easy to send crash reports to Backtrace

Godot Backtrace Module This module adds automatic crash generation support to Godot 3.x with the intent of making it possible to send the crash data t

null 15 Oct 28, 2022