loadstring
Compiles a string of Lua code and returns it as a function.
Syntax
loadstring(code: string, chunkname?: string) -> function?, string?Parameters
| Parameter | Type | Description |
|---|---|---|
code | string | The Lua source code |
chunkname | string? | Optional name for error messages |
Returns
| Type | Description |
|---|---|
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)
endLoading from URL
local code = game:HttpGet("https://example.com/script.lua")
local func, err = loadstring(code)
if func then
func()
endWith 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)
endNamed Chunks
-- Provide a name for better error messages
local func = loadstring("error('test')", "MyScript")
func() -- Error will reference "MyScript"Notes
- Roblox normally disables
loadstringfor security - Volt re-enable this functionality
- Always validate and sanitize code from external sources