Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

string.gmatch #150

Open
markmeeus opened this issue Nov 27, 2022 · 1 comment
Open

string.gmatch #150

markmeeus opened this issue Nov 27, 2022 · 1 comment

Comments

@markmeeus
Copy link
Contributor

There is this closed issue related to string.gmatch:
#43

I would guess that the trickiness of implementing this is the stateful iterator gmatch should return.
Erl_func can't have mutable variables.
However, in Lua a table can be called as well, when it has a __call in its metatable.
So I found a way to implement gmatch in Lua itself:

string.gmatch = function(str, pattern) 
    local callable = {
        nextPos = 0,
        str = str,
        pattern = pattern
    }
    local mt = {}

    function mt.__call(table)            
        match_start, match_end = string.find(table.str, table.pattern, table.nextPos)    
     
        if(match_start == nil) then        
            return nil;
        else
            table.nextPos = match_end + 1;            
            return string.sub(table.str, match_start, match_end)
        end
    end
    
    setmetatable(callable, mt)
    return callable
end


for word in string.gmatch("The big {brown} fox jumped {over} the lazy {dog}.","{(.-)}") do print(word) end

It looks quite possible to implement this in luerl, since all we need to be able to do is in the erl_func:

  • get/set a value in a table
  • string find/sub (which are already implemented)

Would it make sense to implement is like this?

@rvirding
Copy link
Owner

rvirding commented Sep 1, 2023

@markmeeus I am slowly getting around to looking through old stuff. It would be nice to do it in erlang. I checked pairs and ipairs but they return a function to get the next pair. Must think a bit about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants