This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
HPWebcamAble's profile picture

[Pretty much solved] Patterns

Started by HPWebcamAble, 13 July 2015 - 04:38 PM
HPWebcamAble #1
Posted 13 July 2015 - 06:38 PM
For my latest Redstone Engine (The first one might be in my signature),

I save the instructions to a file as code

An example file:

rs.setOutput("right",true)
sleep(1)
rs.setOutput("right",false)

Creating and saving is working great. My problem is reading the code again to be able to edit it.


I'd like to use string patterns to extract the arguments from the functions

Like this:

local func = [[rs.setOutput("right",true)]]

args = { string.match( func , "pattern") }  --# Is it gmatch? EDIT: No, its string.match

print( textutils.serialize( args ) )
Expected Output:

{
  "\"right\"",
  "true",
}


All the functions:
See spoiler below for ones I've completed
(All arguments should be returned as strings, side needs its quotes still)

rs.setOutput("side",state) --#> "side",state
rs.setBundledOutput("side",number) --#> "side",number
rs.setBundledOutput("side",colors.combine(rs.getBundledOutput("side"),number)) --#> "side",number
rs.setBundledOutput("side",colors.subtract(rs.getBundledOutput("side"),number)) --#> "side",number

Spoiler

print( string.match( [[rs.setBundeldOutput("right",120)]] , [[rs.setBundledOutput(%(("a+"),(%d+)%)]] ) --#> "right" , 120 (two variables)
print( string.match( [[rs.setBundledOutput("right",colors.subtract(rs.getBundledOutput("right"),2))]] ,[[rs.setBundledOutput%(("%a+"),colors.subtract%(rs.getBundledOutput%("%a+"%),(%d+)%)%)]]) --#> "right" , 2

NOTE I'd like 4 separate patterns, not one for all 4
( Is one for all 4 even possible? )
Edited on 13 July 2015 - 07:12 PM
Lyqyd #2
Posted 13 July 2015 - 08:31 PM
You may find that you'll need to parse the function arguments character-by-character to catch all of the corner cases (embedded commas, escaped quotes, etc.).

Alternatively, since you're storing valid Lua, you could just loadstring() it.
HPWebcamAble #3
Posted 13 July 2015 - 08:55 PM
Alternatively, since you're storing valid Lua, you could just loadstring() it.

Wow I can't believe that I forgot about that. I actually had a strange idea along those lines…

Could I run it in an environment where the functions, instead of their normal behavior, would add their arguments to a table?



If not, I could still use patterns.

I am terrible at patterns, but I got one working:

code = [[rs.setBundledOutput("right",120)]]

print( string.match( code , [[rs.setBundledOutput(%(("a+"),(%d+)%)]] ) --#> "right" , 120 (two variables, both strings)
Edited on 13 July 2015 - 06:57 PM
Lyqyd #4
Posted 13 July 2015 - 08:59 PM
Yes, you could create an environment that would do that. It would be easiest to construct if you don't need the APIs to contain anything but functions.