Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a lua module set its table's __index as itself?

Tags:

lua

lua-table

I noticed a lua module setting the returned table's __index as itself

local M = {
  _VERSION = "1.0.0"
}
M.__index = M

function M.do()
end

return M

What does setting a table's __index as itself accomplish?

Later, you would use the module

local m = require("m")
m.do()
like image 241
joeforker Avatar asked Sep 03 '25 02:09

joeforker


1 Answers

It is usually done to avoid creating a separate metatable to be used in objects created by the library:

function M.new()
    return setmetatable({},M)
end

I do this all the time in my libraries. It is somewhat lazy.

like image 73
lhf Avatar answered Sep 04 '25 23:09

lhf