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

Call a JavaScript Function Passing an Object Argument

See more JavaScript Examples

Demonstrates how to call a JavaScript function with an argument that is an object.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

-- function describeCar(car) {
--     console.log(`This is a ${car.year} ${car.make} ${car.model}.`);
-- }

local sbScript = chilkat.StringBuilder.new()
sbScript:append("function describeCar(car) { console.log(`This is a ${car.year} ${car.make} ${car.model}.`); }")

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 describeCar(car)

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

-- Create JSON specifying the function name and arguments
-- In this case, there is only 1 argument, and it is an object.

-- {
--   "name": "describeCar",
--   "args": [
--     {
--       "make": "Toyota",
--       "model": "Corolla",
--       "year": 2022
--     }
--   ]
-- }

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

-- Create the JSON object that is the argument.
local arg = chilkat.JsonObject.new()
arg:update_string("make", "Toyota")
arg:update_string("model", "Corolla")
arg:update_int("year", 2022)

-- Create the arguments array.
local argsArray = chilkat.JsonArray.new()
argsArray:add_object_copy_at(0, arg)

-- Add the "args" array to the funcCall.
funcCall:append_array_copy("args", argsArray)

print(funcCall:emit())

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())

-- The describeCar JavaScript function returns nothing.
-- Therefore, the result is "undefined".

-- {
--   "type": "undefined",
--   "value": "undefined"
-- }

-- However, the function emitted text to the console.

local sbOut = chilkat.StringBuilder.new()
js:console_output_sb(sbOut)
print(sbOut:get_as_string())

-- Output:
-- This is a 2022 Toyota Corolla.

-- -----------------------------------------------------------
-- Note: If the object argument is simple, this is an alternative
-- and simpler way of creating the funcCall:

funcCall:clear()
funcCall:update_string("name", "describeCar")
funcCall:update_string("args[0].make", "Toyota")
funcCall:update_string("args[0].model", "Corolla")
funcCall:update_int("args[0].year", 2022)
print(funcCall:emit())