Volt

loadstring

Compiles a string of Lua code and returns it as a function.

Syntax

loadstring(code: string, chunkname?: string) -> function?, string?

Parameters

ParameterTypeDescription
codestringThe Lua source code
chunknamestring?Optional name for error messages

Returns

TypeDescription
function?The compiled function, or nil on error
string?Error message if compilation failed

Description

loadstring compiles Lua source code into a callable function. This is essential for dynamic code execution.

Example

local code = [[
    local message = "Hello from loadstring!"
    print(message)
    return 42
]]

local func, err = loadstring(code)
if func then
    local result = func()
    print("Returned:", result) -- 42
else
    warn("Compile error:", err)
end

Loading from URL

local code = game:HttpGet("https://example.com/script.lua")
local func, err = loadstring(code)
if func then
    func()
end

With Error Handling

local function safeLoadstring(code)
    local func, compileErr = loadstring(code)
    if not func then
        return nil, "Compile error: " .. tostring(compileErr)
    end

    local success, result = pcall(func)
    if not success then
        return nil, "Runtime error: " .. tostring(result)
    end

    return result
end

local result, err = safeLoadstring("return 1 + 1")
if result then
    print("Result:", result)
else
    warn(err)
end

Named Chunks

-- Provide a name for better error messages
local func = loadstring("error('test')", "MyScript")
func() -- Error will reference "MyScript"

Notes

  • Roblox normally disables loadstring for security
  • Volt re-enable this functionality
  • Always validate and sanitize code from external sources

On this page