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

Call a JavaScript Function Returning a String

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a string.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

-- function greet(name) {
--     return "Hello, " + name + "!";
-- }

local sbScript = chilkat.StringBuilder.new()
sbScript:append("function greet(name) { return \"Hello, \" + name + \"!\"; }")

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 greet("Michael")

local funcCall = chilkat.JsonObject.new()

-- Create JSON specifying the function name and arguments

-- {
--   "name": "greet",
--   "args": [ "Michael" ]
-- }

funcCall:update_string("name", "greet")
funcCall:update_string("args[0]", "Michael")

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": "string",
--   "value": "Hello, Michael!"
-- }

local retval = result:string_of("value")
print(retval)

-- Output:
-- Hello, Michael!