Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.4.0+

Call a JavaScript Function Returning an Object

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns an object.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This is the JavaScript function we'll call:

-- function getSettings() {
--     return {
--         theme: "dark",
--         notifications: true,
--         version: 1.0
--     };
-- }

local sbScript = chilkat.StringBuilder.new()
sbScript:append("function getSettings() {")
sbScript:append("    return {")
sbScript:append("        theme: \"dark\",")
sbScript:append("        notifications: true,")
sbScript:append("        version: 1.0")
sbScript:append("    };")
sbScript:append("}")

local js = chilkat.Js.new()

local result = chilkat.JsonObject.new()
result.emit_compact = false

-- Call Eval to add the function to the context's global object
local success = js:eval(sbScript, result)
if not success then
    -- Examine the result for an exception.
    print(result:emit())

    -- Also examine the LastErrorText.
    print(js.last_error_text)
    return
end

-- ------------------------------------------------------------------------------
-- Call the function getSettings()

local funcCall = chilkat.JsonObject.new()

-- Create JSON specifying the function name and arguments
-- The function has no arguments, so we only specify the name.

-- {
--   "name": "getSettings",
-- }

funcCall:update_string("name", "getSettings")

success = js:call_function(funcCall, result)
if not success then
    -- Examine the result for an exception.
    print(result:emit())

    -- Also examine the LastErrorText.
    print(js.last_error_text)
    return
end

print(result:emit())

-- Output:
-- {
--   "type": "object",
--   "value": {
--     "theme": "dark",
--     "notifications": true,
--     "version": 1
--   }
-- }

-- Examine the object's members
print("theme: " .. result:string_of("value.theme"))
print("notifications: " .. tostring(result:bool_of("value.notifications")))
print("version: " .. result:int_of("value.version"))

-- Output:
-- theme: dark
-- notifications: True
-- version: 1