From 8ff082625a64aeb8c583ec98903501c40de11824 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89tienne=20Reuh=20Fildadut?= Date: Mon, 8 Jan 2024 19:39:13 +0100 Subject: [PATCH] Add parse_file and run_file to Lua API --- anselme/init.lua | 10 +++++++++- anselme/state/State.lua | 14 +++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/anselme/init.lua b/anselme/init.lua index ee06797..6c057b2 100644 --- a/anselme/init.lua +++ b/anselme/init.lua @@ -73,11 +73,19 @@ local anselme = { -- Usage: -- ```lua -- local ast = anselme.parse("1 + 2", "test") - -- ast:eval() + -- ast:eval(state) -- ``` parse = function(code, source) return parser(code, source) 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). new = function() return State:new() diff --git a/anselme/state/State.lua b/anselme/state/State.lua index e3060e5..e95edd7 100644 --- a/anselme/state/State.lua +++ b/anselme/state/State.lua @@ -41,6 +41,10 @@ State = class { --- Load standard library. -- 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) local stdlib = require("anselme.stdlib") if language then @@ -173,7 +177,7 @@ State = class { end, --- 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. run = function(self, code, source) @@ -185,6 +189,14 @@ State = class { return "return", r 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. -- -- Will error if no script is active.