In Defold, an engine for developing 2D games across multiple platforms, you can integrate HTML5 specific features using the html5 Lua module. However, as of my last update (April 2023), there's no function specifically named html5.run() in the Defold documentation. Instead, you might be thinking of html5.run() as a way to execute JavaScript code directly from your Lua script, where you can certainly call JavaScript functions with arguments.
If you want to call a JavaScript function with some arguments from Lua in Defold, you generally use the html5.run() method to execute JavaScript code as a string. Here how you can do it:
-
Defining Your JavaScript Function: First, ensure you've got a JavaScript function defined that you'd like to call. This might be something you define in an HTML file that the Defold game is embedded in, or through Defold's custom_html5_shell.html if you're customizing your game shell.
For example, you have a JavaScript function:
function myFunction(arg1, arg2) {
console.log("Arguments received:", arg1, arg2);
// any other logic here
}
-
Calling from Lua: To call this JavaScript function from Lua, use html5.run() like so:
local arg1 = "hello"
local arg2 = 123
-- Remember to properly escape arguments
local js_code = string.format("myFunction('%s', %d);", arg1, arg2)
html5.run(js_code)
-
Escaping Arguments Correctly: Note that in the above Lua code, we are dynamically generating a JavaScript code string. It's essential to properly escape the arguments to avoid injection vulnerabilities or syntax errors. For more complex data types (e.g., objects), consider passing arguments as JSON strings and parsing them inside your JavaScript function.
-
Example with JSON: For more complex cases or when needing to pass an object, you could use JSON:
-
JavaScript side (ensure JSON parsing is implemented):
function myFunctionWithJson(jsonString) {
var args = JSON.parse(jsonString);
console.log(args);
// use args as an object
}
-
Lua side (encoding table as JSON string):
local json = require "json"
local args = {key1 = "value1", key2 = 42}
local argsJson = json.encode(args)
local js_code = string.format("myFunctionWithJson('%s');", argsJson)
html5.run(js_code)
Remember to always consider the security implications of dynamically generating and running code across languages/environments. Avoid directly executing user-generated content to prevent JavaScript injection attacks.