Skip to content

[Feature Request] implement apairs method in go to complement pairs/ipairs #124

Description

@terefang

some custom lua runtimes have the apairs method to complement pairs/ipairs

what apairs basically does it skips over the integer keys and only returns the real hashtable keys

a lua-only implementation is here: https://gist.github.com/jirutka/89eb96b7469a7bfea020

i did some experimenting and found the following go function sufficient

func apairs(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
	if err := c.Check1Arg(); err != nil {
		return nil, err
	}
	next := c.Next()
	_arg := c.Arg(0)
	if _tab, _ok := _arg.TryTable(); _ok {
		var _k rt.Value = rt.NilValue
		var _v rt.Value = rt.NilValue
		var _lk rt.Value = rt.NilValue

		for _ok {
			_k, _v, _ok = _tab.Next(_k)
			if _k.IsNil() ||  _k.TypeName() == "string" {
				break
			}
			_lk = _k
		}
		t.Push1(next, rt.FunctionValue(_next))
		t.Push1(next, _arg)
		t.Push1(next, _lk)
		return next, nil
	}
	return nil, errors.New("not a table")
}

thanks in advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions