Dwij
Dwij

Reputation: 11

lua - How to check if a word is in a string or it is just a word

So I am trying to make a language in lua, and I am replacing the word "output" with "print" and a few more words, but if someone does output("output") it also replaces it. How can i check if it is in a string? Code:

output('trying to make a new language in lua')
output('\n')
local file = io.open(arg[1],"r")
local code = file:read "*a"
local filename = arg[1]
local function execute()
    code = code:gsub("output","print")
  code = code:gsub("void","function")
  code = code:gsub("{}}","end")
  local newfile = io.open(filename:gsub("idk","lua"),"w")
  newfile:write(code)
  newfile:close()
  os.execute("lua test.lua")
end
execute()

Upvotes: 0

Views: 114

Answers (1)

Luatic
Luatic

Reputation: 11201

Lua patterns are generally unsuitable to build a parser for a programming language; neither do they have the full expressive power of regular expressions required for tokenization (lexical analysis) nor do they get anywhere near the power of a context-free grammar (CFG, syntactical analysis) required for constructing the abstract syntax tree even though they provide some advanced features such as bracket matching which exceed regular expression capabilities.

As a beginner, you'll probably want to start with a handwritten tokenizer; as your language only operates at a token replacement level at this stage, you can simply replace identifier tokens.

You don't need string replacement (gsub) to implement variable renames like print to output when you are in control of how the script is executed: Just replace the global print variable with an output variable holding the print function (you may want to do this only in the environment the scripts written in your language run in):

output = print
print = nil

Upvotes: 1

Related Questions