merlin11188

Classes

Jul 1st, 2011
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.22 KB | None | 0 0
  1. --[[Instructions:
  2. Syntax:
  3. _G.class(className){
  4.     Property=value,
  5.     Property=value
  6. }
  7.  
  8. To make a new object of that class type:
  9. ClassName "InheritedClassName"
  10. For people with some experience in other programming languages, everything is inherited, right down
  11. to the values the orginal class had (you can edit those).
  12.  
  13. Want to learn about this script? Read it =P
  14. ]]
  15.  
  16. _G["class"]=function(name)
  17.     return function(arg)
  18.         local s={[name]={}} -- Since this is normal Lua, you can't just make [name] a variable. (Without using getfenv())
  19.         for i,v in pairs(arg) do -- Get all the values
  20.             s[name][i]=v -- Set them
  21.         end
  22.         local Environment=getfenv(2) -- Get the current environment
  23.         Environment[name]=s[name] -- Create the class
  24.         setmetatable(Environment[name], {__index=getfenv(), __newindex=function(t, i, v) -- Set the metatable!
  25.             error("Attempt to index global '"..i.."' (a nil value)", 2) -- This reduces typos (hopefully)
  26.         end,
  27.         __call=function(Object, Name) -- Inheritance; no need for an ugly table!
  28.             getfenv(2)[Name]=Object
  29.         end})
  30.         setfenv(2, Environment) -- Set the new environment
  31.     end
  32. end
  33.  
  34. --Example!:
  35. _G.class("Character"){
  36.     Courage="Arg",
  37.     Power=5,
  38.     Wisdom="10"
  39. }
  40.  
  41. Character "Link"
  42. Link.Power=4
Advertisement
Add Comment
Please, Sign In to add comment