मुझे Lua में कक्षाओं को कठिन समय मिल रहा है। फलहीन गुगल ने मुझे मेटा-टेबल के बारे में विचारों का नेतृत्व किया, और बताया कि कक्षाओं को अनुकरण/लिखने के लिए तीसरे पक्ष के पुस्तकालयों को आवश्यक है।लुआ में कक्षा, उप-वर्ग और संपत्ति कैसे बनाएं?
यहां एक नमूना है (सिर्फ इसलिए कि मैंने देखा है मैं बेहतर जवाब पाने जब मैं नमूना कोड प्रदान करते हैं):
public class ElectronicDevice
{
protected bool _isOn;
public bool IsOn { get { return _isOn; } set { _isOn = value; } }
public void Reboot(){_isOn = false; ResetHardware();_isOn = true; }
}
public class Router : ElectronicDevice
{
}
public class Modem :ElectronicDevice
{
public void WarDialNeighborhood(string areaCode)
{
ElectronicDevice cisco = new Router();
cisco.Reboot();
Reboot();
if (_isOn)
StartDialing(areaCode);
}
}
यहाँ मेरी पहली तकनीक जेवियर ने सुझाव दिया उपयोग करके उपरोक्त अनुवाद करने के लिए प्रयास है।
मैंने आरबीरटेग की सलाह ली। हालांकि, व्युत्पन्न वर्ग पर आमंत्रण अभी भी उपज: "attempt to call method 'methodName' (a nil value)"
--Everything is a table
ElectronicDevice = {};
--Magic happens
mt = {__index=ElectronicDevice};
--This must be a constructor
function ElectronicDeviceFactory()
-- Seems that the metatable holds the fields
return setmetatable ({isOn=true}, mt)
end
-- Simulate properties with get/set functions
function ElectronicDevice:getIsOn() return self.isOn end
function ElectronicDevice:setIsOn(value) self.isOn = value end
function ElectronicDevice:Reboot() self.isOn = false;
self:ResetHardware(); self.isOn = true; end
function ElectronicDevice:ResetHardware() print('resetting hardware...') end
Router = {};
mt_for_router = {__index=Router}
--Router inherits from ElectronicDevice
Router = setmetatable({},{__index=ElectronicDevice});
--Constructor for subclass, not sure if metatable is supposed to be different
function RouterFactory()
return setmetatable ({},mt_for_router)
end
Modem ={};
mt_for_modem = {__index=Modem}
--Modem inherits from ElectronicDevice
Modem = setmetatable({},{__index=ElectronicDevice});
--Constructor for subclass, not sure if metatable is supposed to be different
function ModemFactory()
return setmetatable ({},mt_for_modem)
end
function Modem:WarDialNeighborhood(areaCode)
cisco = RouterFactory();
--polymorphism
cisco.Reboot(); --Call reboot on a router
self.Reboot(); --Call reboot on a modem
if (self.isOn) then self:StartDialing(areaCode) end;
end
function Modem:StartDialing(areaCode)
print('now dialing all numbers in ' .. areaCode);
end
testDevice = ElectronicDeviceFactory();
print("The device is on? " .. (testDevice:getIsOn() and "yes" or "no"));
testDevice:Reboot(); --Ok
testRouter = RouterFactory();
testRouter:ResetHardware(); -- nil value
testModem = ModemFactory();
testModem:StartDialing('123'); -- nil value
क्या आपने [यह] पढ़ा था (http://lua-users.org/wiki/SimpleLuaClasses)? – ThibThib
हाँ और मैंने इसे अपारदर्शी पाया। – MatthewMartin