lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



> On Oct 22, 2023, at 11:29, Tom Sutcliffe <tomsci@me.com> wrote:
> 
> What should something like this do?
> 
> { [1] = "a", [2] = "b", [4] = "d", a = true }

As illustrated by Lars, one way to look at it is to identify the list portion of the table — and iterated everything else.

for aKey, aValue in kpairs( { [1] = "a", [2] = "b", [4] = "d", a = true } ) do
  print( aKey, aValue )
end

a	true
4	d



--8<--

local function kpairs( aTable )
  local aLength = 0 -- #aTable ~= ipairs( aTable )

  for anIndex, _ in ipairs( aTable ) do
    aLength = anIndex
  end

  return coroutine.wrap
  (
    function()
      for aKey, aValue in pairs( aTable ) do
        if not ( math.type( aKey ) == 'integer' and aKey >= 1 and aKey <= aLength ) then coroutine.yield( aKey, aValue ) end
      end
    end
  )
end

for aKey, aValue in kpairs( { [1] = "a", [2] = "b", [4] = "d", a = true } ) do
  print( aKey, aValue )
end

-->8--