简体   繁体   中英

How to rename file object methods

I was trying to duplicate some methods of the file object like so because I need to test a Lua API code using capital case methods insted of lower case. So I tried this:

function openFile(n, m)
  local f = io.open(n, m)
  if(not f) then
    return status(nil,"openFile: Nofile: "..tostring(n))
  end
  f.Read  = f.read
  f.Write = f.write
  f.Close = f.close
  f.Flush = f.flush
  return f
end

Taking into consideration that the file object has file:read , file:write ... aka

But gives me an error like the following:

Execution error:
.\ZeroBraineProjects/dvdlualib/fileapi.lua:41: attempt to index local 'f' (a userdata value)

I thought that a file is simple object table. As it turned out it's a userdata object.

So guys how can I use capital case method for reading and writing ?

You have to set those fields in f 's metatable:

local m = getmetatable(f)
m.Read  = m.read
m.Write = m.write
m.Close = m.close
m.Flush = m.flush

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM