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

A rule for removing (converting) generalized iteration #203

Open
sircfenner opened this issue Jun 18, 2024 · 0 comments · May be fixed by #217
Open

A rule for removing (converting) generalized iteration #203

sircfenner opened this issue Jun 18, 2024 · 0 comments · May be fixed by #217
Labels

Comments

@sircfenner
Copy link

sircfenner commented Jun 18, 2024

See #202 for motivation.

An implementation I have done in the past converts the following:

for x, y, z in input do
    print(x, y, z)
end

into:

local _iterator = input
local _invariant, _control
if type(input) == "table" then
	local _mt = getmetatable(input)
	if type(_mt) == "table" and type(_mt.__iter) == "function" then
		_iterator, _invariant, _control = _mt.__iter(input)
	else
		_iterator, _invariant, _control = pairs(input) -- !
	end
end
for x, y, z in _iterator, _invariant, _control do
	print(x, y, z)
end

This may not be 100% correct but could be a good starting point.

As it can't be determined statically whether the subject of iteration is (1) a plain table, (2) an iterator function, or (3) a table with an __iter metamethod defined, it is necessary to insert a runtime check.

Notes:

  1. Using pairs(input) does not necessarily conform to the order of Luau generic iteration (for example, consecutive array indices starting from 1 go first)
  2. Doesn't handle iterating over userdata (with __iter defined), which is supported by Luau
  3. There may also be issues with accessing __iter if __metatable is set
@jiwonz jiwonz linked a pull request Sep 27, 2024 that will close this issue
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants