how send table to js in lua script? (defold engine)
- User
how send table to js in lua script? (defold engine)
- Assistant
how send table to js in lua script? (defold engine)
In Defold, which is a game engine primarily used for developing 2D games for desktop, mobile, and web platforms, communication between Lua scripts and JavaScript (typically for HTML5 builds) can be achieved using the html5.run() function and messaging. However, directly sending a Lua table as-is to JavaScript through these means isn't straightforward due to differences in data structures between Lua and JavaScript.
One common approach is to serialize the Lua table to a JSON string, send this string to JavaScript, and then parse the JSON string back into a JavaScript object. Lua does not include native support for JSON serialization, but Defold provides a simple JSON API through json.encode() for this purpose.
In your Lua script, you first need to convert your table into a JSON string. Assume you have a table like this:
local myTable = {
name = "Defold",
version = 1.2,
features = {"Cross-platform", "2D", "Lightweight"}
}
You convert this table to a JSON string using json.encode():
local jsonString = json.encode(myTable)
Using html5.run(), you can execute JavaScript code directly from Lua. You'll pass the JSON string as a parameter to JavaScript. Due to how html5.run() constructs the JavaScript code to run, you need to ensure your JSON string is properly embedded in the JavaScript code, typically by enclosing it in quotes. However, since JSON strings can contain quotes, you also need to escape them:
-- Ensure the JSON string is properly escaped for JavaScript
local escapedJsonString = jsonString:gsub('"', '\\"')
html5.run(string.format([[handleDataFromLua("%s")]], escapedJsonString))
In your game's HTML5 page, you have to define the JavaScript function handleDataFromLua() that was called from Lua:
function handleDataFromLua(jsonString) {
var dataFromLua = JSON.parse(jsonString);
console.log("Received from Lua: ", dataFromLua);
// Now, dataFromLua is a JavaScript object that you can work with
}
This technique allows you to serialize complex Lua tables and send them over to JavaScript as strings, then deserialize them back into JavaScript objects, which can then be manipulated as needed in the JavaScript environment.
Remember, working with JSON is convenient for data exchange, but ensure that any data you serialize does not contain circular references as JSON does not support them. For Lua tables with non-string keys, be mindful that JSON object keys can only be strings, so such keys will either be converted to strings or excluded, depending on the serialization implementation.
Not yet included in a published release.