1. 程式人生 > >Lua中常見遇到的問題解決方案

Lua中常見遇到的問題解決方案

require "uiDefine"

報錯資訊:module 'uiDefine' not found:

no fieldpackage.preload['uiDefine']

no such builtin lib'uiDefine'

解決方法: 在require "ui.uiDefine" 在基於lua根目錄的下require全路徑,例如Assets/Scripts/lua為根目錄

static public class UnityCommonExtension

{

static public void DestroyAllChildren(this GameObject target)

           {

       foreach (Transform child in target.transform)

       {

            GameObject.Destroy(child.gameObject);

       }

    }

}

for i = 1, #headIconParent do

                   headIconParent[i]:DestroyAllChildren()

End

         如果

public static class LuaGenConfig

{

   //lua中要使用到C#庫的配置,比如C#標準庫,或者UnityAPI,第三方庫等。

   [LuaCallCSharp

]

   public static List<TypeLuaCallCSharp = new List<Type>()

{

//typeof(UnityCommonExtension),

}

}

報錯資訊: attemptto call a nil value (method 'DestroyAllChildren')

解決方法:

for i = 1, #headIconParent do

                   CS.UnityCommonExtension.DestroyAllChildren(headIconParent[i])

End

或者 LuaGenConfig新增上,然後用 

headIconParent[i]:DestroyAllChildren()

或 headIconParent[i].DestroyAllChildren(headIconParent[i])即可

for i = 1, pairs(headIconParent) do end

報錯資訊:'for'limit must be a number

解決方法:用 for i= 1, #headIconParent do end

而for k, v pairs(headIconParent) do end 也可以

C# 的陣列傳到lua裡,

local widgets = {}--go:GetComponentsInChildren("UIWidget",true)    

           local widArr =InterfaceForLua.GetWidgetArray(go)

           for i = 0, widArr.Length - 1 do

             table.insert(widgets, widArr[i])

           end

但是c#的list傳到lua裡就不能被識別。

如果定義的是方法,要寫function()#### end, 否則不寫會執行呼叫的函式,而不是傳進去的方法。

定義的 lua方法,:定義:呼叫,.定義.呼叫 , :也用在c#靜態方法的呼叫,省去self

function UIItemIconInfo:CreateItemIcon(itemNum, parent, uniqueName)

         local go =ResUtil.LoadGameObject("UI/CommonIcon/ItemIconInfoLua")

    local script = {}

         setmetatable(script,{__index = UIItemIconInfo}

script.gameObject = go

    script.Data = itemNum

         script.eName =uniqueName

         script:InitEvent()

    script:awake()

    script:onBindComplete()

script:start()

    if parent ~= nil then

     parent:AddChildEx(go.transform)

    end

    go.name =string.format("Item%s", tostring(itemNum.ItemId))

    if parent ~= nil andparent:GetComponent("UIWidget") ~= nil then

      local parentDepth =parent:GetComponent("UIWidget").depth

      local widgets = {}   localwidArr = InterfaceForLua.GetWidgetArray(go)

           for i = 0, widArr.Length - 1 do

             table.insert(widgets, widArr[i])

           end

           for k in pairs(widgets) do

                   widgets[k].depth= widgets[k].depth + parentDepth

           end

    end

         return script

end

function UIItemIconInfo:onBindComplete()

  self:SetMask(false)

  self:ItemIconCanClick(true)

 self:AddDragScrollView(false, nil)

 self:SetItemIconScale(Vector3.one)

 self:SetBackGroundVisable(true, true)

         self:SetSelectHide(true)

end

function UIItemIconInfo:SetMask(bVis)

  Mask:SetActive(bVis)

End

self 與單例的使用

這些就是lua單例的使用方法

local widgets = {}

local widArr = InterfaceForLua.GetWidgetArray(go) –這個是c#傳過來的UIWidget[]

logError(typeof(widgets).."  "..typeof(widArr))  --  table  userdata

--widgets = widArr  --如果能成功,表相等,是引用,一個改另一個跟著改

         table.insert(widgets,widArr) --如果能成功,表insert,是獨立的表

報錯資訊:attemptto get length of a userdata value

解決方法:遍歷userdata,進行插入表

for i = 0, widArr.Length - 1 do

         table.insert(widgets,widArr[i])

end

---------for迴圈

for i = 1, #widgets do

widgets[i].depth = widgets[i].depth + parentDepth

end

for k in pairs(widgets) do

print(k)

         widgets[k].depth = widgets[k].depth +parentDepth

end

-------這兩個一樣的作用

local widArr = InterfaceForLua.GetWidgetArray(go)  加入local 變數  widArr.Length獲取長度 5.2之前table.getn

LuaException: ui.CommonIcon.UIItemIconInfoLua:157: attempt toperform arithmetic on a nil value (field 'depth')

stack traceback:

         ui.CommonIcon.UIItemIconInfoLua:157:in field 'CreateItemIcon'

解決方法:

LuaException: c# exception:Non-static method requires atarget.,stack:  atSystem.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlagsinvokeAttr, System.Reflection.Binder binder, System.Object[] parameters,System.Globalization.CultureInfo culture) [0x000fe] in/Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:236

  atSystem.Reflection.MethodBase.Invoke (System.Object obj, System.Object[]parameters) [0x00000] in/Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MethodBase.cs:115

  atXLua.OverloadMethodWrap.Call (IntPtr L) [0x00151] inE:\redemption\project\client\redemptionV2\Assets\XLua\Src\MethodWarpsCache.cs:220

  at XLua.MethodWrap.Call(IntPtr L) [0x00036] inE:\redemption\project\client\redemptionV2\Assets\XLua\Src\MethodWarpsCache.cs:260

stack traceback:

         [C]: in field'SetActive'

解決方法:'SetActive'不是static方法,要用:訪問

UIItemIconInfo script = go:GetComponent('UIItemIconInfo')

報錯資訊:syntax error near 'script'

解決方法:宣告為local即可

go.transform.localScale =CS.UnityEngine.Vector3(0.7f, 0.7f, 0.7f) (lua中沒有new)

報錯資訊:malformed number near '0.7f'

解決方法:把f去掉,lua沒有integer和float型別之分,數值都是用number型別表示的,

attempt to perform arithmetic on a stringvalue

stack traceback:

解決方案:這個寫成的c#的語法了,把+ 變成.. 例如print("AAAAAAAAbbb: " + tostring(Data.Reward.Count))

LuaException: error loading modulecoruntine_test from resource, coruntine_test.lua:29: syntax error near 'local'

stack traceback:

         [C]:in ?

         [C]:in function 'require'

         [string"chunk"]:1: in main chunk

解決方法:29行呼叫到地方檢查,就到了require 的地方,比如檢查 = 號賦值

LuaException: [string"LuaBehaviour"]:32: attempt to index a thread value (global 'co')

stack traceback:

         [string"LuaBehaviour"]:32: in function <[string"LuaBehaviour"]:22>

XLua.LuaEnv.ThrowExceptionFromError (Int32oldTop) (at Assets/XLua/Src/LuaEnv.cs:411)

XLuaGenDelegateImpl0.Invoke7(UnityEngine.GameObject go)

UIEventListener.OnClick () (atAssets/NGUI/Scripts/Internal/UIEventListener.cs:53)

解決方法:直接呼叫 lua 的協程報錯, 然後用包裝 Unity 協程 的方法解決

table.getn()提示 attempt to call a nil value (field'getn')

解決方法:Usethe length operator #asin #foo.

table.getnwasdeprecated in 5.1 and removed in 5.2.

functiontable.getn(x) local ret for i in pairs(x) do ret=ret+1 end return ret end

InvalidCastException: This interface mustadd to CSharpCallLua: UIItemIconInfo+myInter

XLua.CodeEmit.EmitInterfaceImpl(System.Type to_be_impl) (at Assets/ThirdParty/XLua/Src/CodeEmit.cs:349)

XLua.ObjectTranslator.CreateInterfaceBridge(IntPtr L, System.Type interfaceType, Int32 idx) (atAssets/ThirdParty/XLua/Src/ObjectTranslator.cs:436)

XLua.ObjectCasters+<genCaster>c__AnonStorey0.<>m__2(IntPtr L, Int32 idx, System.Object target) (atAssets/ThirdParty/XLua/Src/ObjectCasters.cs:447)

XLua.ObjectTranslator.GetObject (IntPtr L,Int32 index, System.Type type) (atAssets/ThirdParty/XLua/Src/ObjectTranslator.cs:656)

XLua.ObjectTranslator.Get[myInter] (IntPtrL, Int32 index, myInter& v) (atAssets/ThirdParty/XLua/Src/ObjectTranslator.cs:669)

解決方法:加上[CSharpCallLua]

LuaException:assets/bundles//lua/logicBase/GenerateLuaData.lua:6: attempt to index a nilvalue (global 'GenerateLuaData')

stack traceback:

         assets/bundles//lua/logicBase/GenerateLuaData.lua:6:in main chunk

         [C]:in function 'require'

         assets/bundles//lua/logicBase/EnterLua.lua:4:in main chunk

         [C]:in function 'require'

         E:/redemptionV2_XLua/Assets/LuaFramework/Lua/Main.lua:2:in main chunk

         [C]:in function 'require'

         [string"chunk"]:1: in main chunk

XLua.LuaEnv.ThrowExceptionFromError (Int32oldTop) (at Assets/ThirdParty/XLua/Src/LuaEnv.cs:411)

XLua.LuaEnv.DoString (System.String chunk,System.String chunkName, XLua.LuaTable env) (atAssets/ThirdParty/XLua/Src/LuaEnv.cs:248)

LuaFramework.LuaManager.StartMain () (atAssets/LuaFramework/Scripts/Manager/LuaManager.cs:52)

LuaFramework.LuaManager.InitStart () (atAssets/LuaFramework/Scripts/Manager/LuaManager.cs:21)

LuaFramework.GameManager.OnInitialize ()(at Assets/LuaFramework/Scripts/Manager/GameManager.cs:252)

LuaFramework.GameManager.OnResourceInited() (at Assets/LuaFramework/Scripts/Manager/GameManager.cs:247)

LuaFramework.GameManager+<OnUpdateResource>c__Iterator1.MoveNext() (at Assets/LuaFramework/Scripts/Manager/GameManager.cs:133)

UnityEngine.SetupCoroutine.InvokeMoveNext(IEnumerator enumerator, IntPtr returnValueAddress) (atC:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)

LuaFramework.GameManager:CheckExtractResource()(at Assets/LuaFramework/Scripts/Manager/GameManager.cs:58)