1
0
Fork 0
mirror of https://github.com/Reuh/anselme.git synced 2025-10-27 16:49:31 +00:00

Add parse_file and run_file to Lua API

This commit is contained in:
Étienne Fildadut 2024-01-08 19:39:13 +01:00
parent bd93dc43dc
commit 8ff082625a
2 changed files with 22 additions and 2 deletions

View file

@ -73,11 +73,19 @@ local anselme = {
-- Usage: -- Usage:
-- ```lua -- ```lua
-- local ast = anselme.parse("1 + 2", "test") -- local ast = anselme.parse("1 + 2", "test")
-- ast:eval() -- ast:eval(state)
-- ``` -- ```
parse = function(code, source) parse = function(code, source)
return parser(code, source) return parser(code, source)
end, end,
--- Same as `:parse`, but read the code from a file.
-- `source` will be set as the file path.
parse_file = function(path)
local f = assert(io.open(path, "r"))
local block = parser(f:read("a"), path)
f:close()
return block
end,
--- Return a new [State](#state). --- Return a new [State](#state).
new = function() new = function()
return State:new() return State:new()

View file

@ -41,6 +41,10 @@ State = class {
--- Load standard library. --- Load standard library.
-- You will probably want to call this on every State right after creation. -- You will probably want to call this on every State right after creation.
--
-- Optionally, you can specify `language` (string) to instead load a translated version of the standaring library. Available translations:
--
-- * `"frFR"`
load_stdlib = function(self, language) load_stdlib = function(self, language)
local stdlib = require("anselme.stdlib") local stdlib = require("anselme.stdlib")
if language then if language then
@ -173,7 +177,7 @@ State = class {
end, end,
--- Load a script in this branch. It will become the active script. --- Load a script in this branch. It will become the active script.
-- --
-- `code` is the code string or AST to run, `source` is the source name string to show in errors (optional). -- `code` is the code string or AST to run. If `code` is a string, `source` is the source name string to show in errors (optional).
-- --
-- Note that this will only load the script; execution will only start by using the `:step` method. Will error if a script is already active in this State. -- Note that this will only load the script; execution will only start by using the `:step` method. Will error if a script is already active in this State.
run = function(self, code, source) run = function(self, code, source)
@ -185,6 +189,14 @@ State = class {
return "return", r return "return", r
end) end)
end, end,
--- Same as `:run`, but read the code from a file.
-- `source` will be set as the file path.
run_file = function(self, path)
local f = assert(io.open(path, "r"))
local block = parser(f:read("a"), path)
f:close()
return self:run(block)
end,
--- When a script is active, will resume running it until the next event. --- When a script is active, will resume running it until the next event.
-- --
-- Will error if no script is active. -- Will error if no script is active.