chore: initialize UE 5.8 + UnLua game framework project

This commit is contained in:
szy73711 committed 2026-11-28 01:45:03 +08:00
commit 943af16954
397 files changed
+95588

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
# Normalize text files line endings
* text=auto
# C++ / C# / Lua / Config / Scripts
*.h text eol=lf
*.hpp text eol=lf
*.c text eol=lf
*.cpp text eol=lf
*.cs text eol=lf
*.lua text eol=lf
*.ini text eol=lf
*.uproject text eol=lf
*.uplugin text eol=lf
*.json text eol=lf
*.md text eol=lf
*.sh text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
# Unreal Engine binary assets
*.uasset binary
*.umap binary
*.upk binary
*.udk binary
*.ubulk binary
*.uptnl binary
*.pak binary
*.utoc binary
*.ucas binary
# Media & 3D binary assets
*.png binary
*.jpg binary
*.jpeg binary
*.tga binary
*.bmp binary
*.psd binary
*.exr binary
*.hdr binary
*.wav binary
*.ogg binary
*.mp3 binary
*.mp4 binary
*.fbx binary
*.obj binary
*.ttf binary
*.otf binary
+84
View File
@@ -0,0 +1,84 @@
# ==============================================================================
# Unreal Engine 5.8 + UnLua Project .gitignore
# ==============================================================================
# --- Unreal Engine Generated Directories ---
Binaries/
DerivedDataCache/
Intermediate/
Saved/
Build/
StagedBuilds/
ArchivedBuilds/
Releases/
LocalBuilds/
Platforms/*/Intermediate/
Platforms/*/Binaries/
# --- Plugin Generated Directories ---
Plugins/*/Binaries/
Plugins/*/DerivedDataCache/
Plugins/*/Intermediate/
Plugins/*/Saved/
Plugins/*/Source/**/obj/
Plugins/*/Source/**/bin/
*.ubtplugin.csproj.props
# --- UnLua Generated IntelliSense & Local HotUpdate Output ---
Content/Script/IntelliSense/
HotUpdateOutput/
*.luac
# --- IDE & Project Files (Xcode / Visual Studio / Rider / VSCode) ---
*.xcodeproj/
*.xcworkspace/
*.sln
*.sln.iml
*.suo
*.user
*.opensdf
*.sdf
*.VC.db
*.VC.opendb
*.vcxproj
*.vcxproj.filters
*.vcxproj.user
*.code-workspace
.vs/
.vscode/
.idea/
.gradle/
.clangd/
.cache/
compile_commands.json
*.DotSettings.user
# --- Debug Symbols, Dumps & Packaging Artifacts ---
*.pdb
!Plugins/UnLua/Source/ThirdParty/Lua/**/*.pdb
*.dSYM/
*.dmp
*.crash
*.app/
*.ipa
*.apk
*.aab
# --- Logs & Temporary Files ---
*.log
*.tmp
*.bak
*.orig
*.swp
*.swo
*~
# --- OS Specific Files ---
.DS_Store
.AppleDouble
.LSOverride
._*
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
+2
View File
@@ -0,0 +1,2 @@
[/Script/UnrealEd.EditorEngine]
; Default editor settings for UnrealLuaDemo
+39
View File
@@ -0,0 +1,39 @@
[/Script/EngineSettings.GameMapsSettings]
GameDefaultMap=/Engine/Maps/Templates/Template_Default
EditorStartupMap=/Engine/Maps/Templates/Template_Default
GlobalDefaultGameMode=/Script/UnrealLuaDemo.LuaGameModeBase
GameInstanceClass=/Script/UnrealLuaDemo.LuaGameInstance
[/Script/Engine.RendererSettings]
r.AllowStaticLighting=False
r.Shadow.Virtual.Enable=1
[/Script/WindowsTargetPlatform.WindowsTargetSettings]
DefaultGraphicsRHI=DefaultGraphicsRHI_DX12
-D3D12TargetedShaderFormats=PCD3D_SM5
+D3D12TargetedShaderFormats=PCD3D_SM6
-D3D11TargetedShaderFormats=PCD3D_SM5
+D3D11TargetedShaderFormats=PCD3D_SM5
[/Script/LinuxTargetPlatform.LinuxTargetSettings]
-TargetedRHIs=SF_VULKAN_SM5
+TargetedRHIs=SF_VULKAN_SM6
[/Script/MacTargetPlatform.MacTargetSettings]
-TargetedRHIs=SF_METAL_SM5
+TargetedRHIs=SF_METAL_SM6
[/Script/AndroidFileServerEditor.AndroidFileServerRuntimeSettings]
bEnablePlugin=True
bAllowNetworkConnection=True
SecurityToken=6E53E8D5904A8A835DA61DA874CF036B
bIncludeInShipping=False
bAllowExternalStartInShipping=False
bCompileAFSProject=False
bUseCompression=False
bLogFiles=False
bReportStats=False
ConnectionType=USBOnly
bUseManualIPAddress=False
ManualIPAddress=
+111
View File
@@ -0,0 +1,111 @@
[/Script/EngineSettings.GeneralProjectSettings]
ProjectName=UnrealLuaDemo
Description=UE 5.8 Game Framework with UnLua Hot-Update Support
ProjectVersion=0.1.0.0
[/Script/UnrealEd.ProjectPackagingSettings]
Build=IfProjectHasCode
BuildConfiguration=PPBC_Development
BuildTarget=
FullRebuild=False
ForDistribution=False
IncludeDebugFiles=False
UsePakFile=True
bUseIoStore=True
bUseZenStore=True
bMakeBinaryConfig=False
bGenerateChunks=False
bGenerateNoChunks=False
bChunkHardReferencesOnly=False
bForceOneChunkPerFile=False
MaxChunkSize=0
bBuildHttpChunkInstallData=False
HttpChunkInstallDataDirectory=(Path="")
WriteBackMetadataToAssetRegistry=Disabled
bWritePluginSizeSummaryJsons=False
bCompressed=True
PackageCompressionFormat=Oodle
bForceUseProjectCompressionFormatIgnoreHardwareOverride=False
PackageAdditionalCompressionOptions=
PackageCompressionMethod=Kraken
PackageCompressionLevel_DebugDevelopment=4
PackageCompressionLevel_TestShipping=4
PackageCompressionLevel_Distribution=7
PackageCompressionMinBytesSaved=1024
PackageCompressionMinPercentSaved=5
bPackageCompressionEnableDDC=False
PackageCompressionMinSizeToConsiderDDC=0
HttpChunkInstallDataVersion=
IncludePrerequisites=True
IncludeAppLocalPrerequisites=False
bShareMaterialShaderCode=True
bDeterministicShaderCodeOrder=False
bSharedMaterialNativeLibraries=False
ApplocalPrerequisitesDirectory=(Path="")
IncludeCrashReporter=False
InternationalizationPreset=English
-CulturesToStage=en
+CulturesToStage=en
LocalizationTargetCatchAllChunkId=0
bCookAll=False
bCookMapsOnly=False
bTreatWarningsAsErrorsOnCook=False
bSkipEditorContent=False
bSkipMovies=False
-IniKeyDenylist=KeyStorePassword
-IniKeyDenylist=KeyPassword
-IniKeyDenylist=DebugKeyStorePassword
-IniKeyDenylist=DebugKeyPassword
-IniKeyDenylist=rsa.privateexp
-IniKeyDenylist=rsa.modulus
-IniKeyDenylist=rsa.publicexp
-IniKeyDenylist=aes.key
-IniKeyDenylist=SigningPublicExponent
-IniKeyDenylist=SigningModulus
-IniKeyDenylist=SigningPrivateExponent
-IniKeyDenylist=EncryptionKey
-IniKeyDenylist=DevCenterUsername
-IniKeyDenylist=DevCenterPassword
-IniKeyDenylist=IOSTeamID
-IniKeyDenylist=SigningCertificate
-IniKeyDenylist=MobileProvision
-IniKeyDenylist=AppStoreConnectKeyPath
-IniKeyDenylist=AppStoreConnectIssuerID
-IniKeyDenylist=AppStoreConnectKeyID
-IniKeyDenylist=IniKeyDenylist
-IniKeyDenylist=IniSectionDenylist
+IniKeyDenylist=KeyStorePassword
+IniKeyDenylist=KeyPassword
+IniKeyDenylist=DebugKeyStorePassword
+IniKeyDenylist=DebugKeyPassword
+IniKeyDenylist=rsa.privateexp
+IniKeyDenylist=rsa.modulus
+IniKeyDenylist=rsa.publicexp
+IniKeyDenylist=aes.key
+IniKeyDenylist=SigningPublicExponent
+IniKeyDenylist=SigningModulus
+IniKeyDenylist=SigningPrivateExponent
+IniKeyDenylist=EncryptionKey
+IniKeyDenylist=DevCenterUsername
+IniKeyDenylist=DevCenterPassword
+IniKeyDenylist=IOSTeamID
+IniKeyDenylist=SigningCertificate
+IniKeyDenylist=MobileProvision
+IniKeyDenylist=AppStoreConnectKeyPath
+IniKeyDenylist=AppStoreConnectIssuerID
+IniKeyDenylist=AppStoreConnectKeyID
+IniKeyDenylist=IniKeyDenylist
+IniKeyDenylist=IniSectionDenylist
-IniSectionDenylist=HordeStorageServers
-IniSectionDenylist=StorageServers
-IniSectionDenylist=/Script/AndroidFileServerEditor.AndroidFileServerRuntimeSettings
+IniSectionDenylist=HordeStorageServers
+IniSectionDenylist=StorageServers
+IniSectionDenylist=/Script/AndroidFileServerEditor.AndroidFileServerRuntimeSettings
+DirectoriesToAlwaysCook=(Path="/NNEDenoiser")
+DirectoriesToAlwaysStageAsUFS=(Path="Script")
+DirectoriesToAlwaysStageAsUFS=(Path="../Plugins/UnLua/Content/Script")
+DirectoriesToAlwaysStageAsNonUFS=(Path="Script")
bRetainStagedDirectory=False
CustomStageCopyHandler=
+84
View File
@@ -0,0 +1,84 @@
[/Script/Engine.InputSettings]
-AxisConfig=(AxisKeyName="Gamepad_LeftX",AxisProperties=(DeadZone=0.25,Exponent=1.f,Sensitivity=1.f))
-AxisConfig=(AxisKeyName="Gamepad_LeftY",AxisProperties=(DeadZone=0.25,Exponent=1.f,Sensitivity=1.f))
-AxisConfig=(AxisKeyName="Gamepad_RightX",AxisProperties=(DeadZone=0.25,Exponent=1.f,Sensitivity=1.f))
-AxisConfig=(AxisKeyName="Gamepad_RightY",AxisProperties=(DeadZone=0.25,Exponent=1.f,Sensitivity=1.f))
-AxisConfig=(AxisKeyName="MouseX",AxisProperties=(DeadZone=0.f,Exponent=1.f,Sensitivity=0.07f))
-AxisConfig=(AxisKeyName="MouseY",AxisProperties=(DeadZone=0.f,Exponent=1.f,Sensitivity=0.07f))
-AxisConfig=(AxisKeyName="Mouse2D",AxisProperties=(DeadZone=0.f,Exponent=1.f,Sensitivity=0.07f))
+AxisConfig=(AxisKeyName="Gamepad_LeftX",AxisProperties=(DeadZone=0.250000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_LeftY",AxisProperties=(DeadZone=0.250000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_RightX",AxisProperties=(DeadZone=0.250000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_RightY",AxisProperties=(DeadZone=0.250000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MouseX",AxisProperties=(DeadZone=0.000000,Sensitivity=0.070000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MouseY",AxisProperties=(DeadZone=0.000000,Sensitivity=0.070000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Mouse2D",AxisProperties=(DeadZone=0.000000,Sensitivity=0.070000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MouseWheelAxis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_LeftTriggerAxis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_RightTriggerAxis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_Special_Left_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Gamepad_Special_Left_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Vive_Left_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Vive_Left_Trackpad_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Vive_Left_Trackpad_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Vive_Right_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Vive_Right_Trackpad_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="Vive_Right_Trackpad_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Left_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Left_Thumbstick_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Left_Thumbstick_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Left_Trackpad_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Left_Trackpad_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Right_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Right_Thumbstick_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Right_Thumbstick_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Right_Trackpad_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="MixedReality_Right_Trackpad_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Left_Grip_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Left_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Left_Thumbstick_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Left_Thumbstick_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Right_Grip_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Right_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Right_Thumbstick_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="OculusTouch_Right_Thumbstick_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Grip_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Grip_Force",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Thumbstick_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Thumbstick_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Trackpad_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Trackpad_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Left_Trackpad_Force",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Grip_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Grip_Force",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Trigger_Axis",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Thumbstick_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Thumbstick_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Trackpad_X",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Trackpad_Y",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
+AxisConfig=(AxisKeyName="ValveIndex_Right_Trackpad_Force",AxisProperties=(DeadZone=0.000000,Sensitivity=1.000000,Exponent=1.000000,bInvert=False))
bAltEnterTogglesFullscreen=True
bF11TogglesFullscreen=True
bUseMouseForTouch=False
bEnableMouseSmoothing=True
bEnableFOVScaling=True
bCaptureMouseOnLaunch=True
bEnableLegacyInputScales=True
bEnableMotionControls=True
bFilterInputByPlatformUser=False
bShouldFlushPressedKeysOnViewportFocusLost=True
bAlwaysShowTouchInterface=False
bShowConsoleOnFourFingerTap=True
bEnableGestureRecognizer=False
bUseAutocorrect=False
DefaultViewportMouseCaptureMode=CapturePermanently_IncludingInitialMouseDown
DefaultViewportMouseLockMode=LockOnCapture
FOVScale=0.011110
DoubleClickTime=0.200000
DefaultPlayerInputClass=/Script/EnhancedInput.EnhancedPlayerInput
DefaultInputComponentClass=/Script/EnhancedInput.EnhancedInputComponent
DefaultTouchInterface=/Engine/MobileResources/HUD/DefaultVirtualJoysticks.DefaultVirtualJoysticks
-ConsoleKeys=Tilde
+ConsoleKeys=Tilde
+16
View File
@@ -0,0 +1,16 @@
[/Script/UnLuaEditor.UnLuaEditorSettings]
bAutoStartup=True
bEnableDebug=False
bEnablePersistentParamBuffer=True
bEnableTypeChecking=True
bEnableUnrealInsights=False
bEnableCallOverriddenFunction=True
bEnableFText=False
bLuaCompileAsCpp=False
bWithUE4Namespace=True
bLegacyReturnOrder=False
bLegacyBlueprintPath=False
bLegacyAllowUTF8WithBOM=False
bLegacyArgsPassing=True
LuaVersion=lua-5.4.3
HotReloadMode=Manual
+37
View File
@@ -0,0 +1,37 @@
---@class Framework.Bootstrap
---Central Lua game framework bootstrapper initialized by ULuaGameInstance.
local Log = require("Framework.Log")
local EventBus = require("Framework.EventBus")
local HotReload = require("Framework.HotReload")
local Bootstrap = {
Version = "0.1.0",
IsInitialized = false,
GameInstance = nil,
}
---@param gameInstance ULuaGameInstance
function Bootstrap.Init(gameInstance)
Bootstrap.GameInstance = gameInstance
Bootstrap.IsInitialized = true
_G.GameFramework = {
Log = Log,
EventBus = EventBus,
HotReload = HotReload,
Bootstrap = Bootstrap,
GameInstance = gameInstance,
}
Log.Info("Lua GameFramework initialized (version=%s, Lua=%s)", Bootstrap.Version, _VERSION)
end
function Bootstrap.Shutdown()
Log.Info("Lua GameFramework shutting down...")
EventBus.Clear()
Bootstrap.GameInstance = nil
Bootstrap.IsInitialized = false
_G.GameFramework = nil
end
return Bootstrap
+94
View File
@@ -0,0 +1,94 @@
---@class Framework.EventBus
---Lightweight publish/subscribe event bus for decoupled Lua game systems.
local EventBus = {}
local Listeners = {}
---@param eventName string
---@param callback function
---@param owner any|nil
function EventBus.On(eventName, callback, owner)
assert(type(eventName) == "string", "EventBus.On: eventName must be a string")
assert(type(callback) == "function", "EventBus.On: callback must be a function")
local list = Listeners[eventName]
if not list then
list = {}
Listeners[eventName] = list
end
for _, entry in ipairs(list) do
if entry.callback == callback and entry.owner == owner then
return
end
end
list[#list + 1] = {
callback = callback,
owner = owner,
}
end
---@param eventName string
---@param callback function
---@param owner any|nil
function EventBus.Off(eventName, callback, owner)
local list = Listeners[eventName]
if not list then
return
end
for i = #list, 1, -1 do
local entry = list[i]
if entry.callback == callback and (owner == nil or entry.owner == owner) then
table.remove(list, i)
end
end
end
---@param owner any
function EventBus.OffAllForOwner(owner)
if owner == nil then
return
end
for _, list in pairs(Listeners) do
for i = #list, 1, -1 do
if list[i].owner == owner then
table.remove(list, i)
end
end
end
end
---@param eventName string
function EventBus.Emit(eventName, ...)
local list = Listeners[eventName]
if not list then
return
end
-- Snapshot to allow listeners to unsubscribe during dispatch
local snapshot = {}
for i = 1, #list do
snapshot[i] = list[i]
end
for i = 1, #snapshot do
local entry = snapshot[i]
local ok, err
if entry.owner ~= nil then
ok, err = pcall(entry.callback, entry.owner, ...)
else
ok, err = pcall(entry.callback, ...)
end
if not ok then
print(string.format("[UnrealLuaDemo][ERROR] EventBus(%s): %s", eventName, tostring(err)))
end
end
end
function EventBus.Clear()
Listeners = {}
end
return EventBus
+57
View File
@@ -0,0 +1,57 @@
---@class Framework.HotReload
---Coordinates Lua module hot-reloading with UnLua and notifies listeners.
local Log = require("Framework.Log")
local EventBus = require("Framework.EventBus")
local HotReload = {}
HotReload.EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload"
HotReload.EVENT_AFTER_RELOAD = "Framework.AfterHotReload"
---Reloads a specific Lua module (clears package.loaded and re-requires it).
---@param moduleName string Dot-separated Lua module name, e.g. "Game.LuaGameMode"
---@return boolean ok
---@return any resultOrErr
function HotReload.ReloadModule(moduleName)
if type(moduleName) ~= "string" or moduleName == "" then
return false, "Invalid module name"
end
Log.Info("Hot-reloading Lua module: %s", moduleName)
EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, moduleName)
package.loaded[moduleName] = nil
local ok, result = pcall(require, moduleName)
if not ok then
Log.Error("Failed to hot-reload module '%s': %s", moduleName, tostring(result))
return false, result
end
EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, moduleName, result)
Log.Info("Successfully hot-reloaded Lua module: %s", moduleName)
return true, result
end
---Triggers UnLua's built-in hot reload across all loaded modules.
---@return boolean ok
function HotReload.ReloadAll()
Log.Info("Triggering full UnLua HotReload...")
EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, "*")
if UnLua and type(UnLua.HotReload) == "function" then
local ok, err = pcall(UnLua.HotReload)
if not ok then
Log.Error("UnLua.HotReload() failed: %s", tostring(err))
return false
end
else
Log.Warn("UnLua.HotReload is unavailable; skipping global hot reload.")
return false
end
EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "*")
Log.Info("UnLua HotReload completed.")
return true
end
return HotReload
+26
View File
@@ -0,0 +1,26 @@
---@class Framework.Log
local Log = {}
local TAG = "[UnrealLuaDemo]"
local function FormatMessage(level, fmt, ...)
local ok, msg = pcall(string.format, tostring(fmt), ...)
if not ok then
msg = tostring(fmt)
end
return string.format("%s[%s] %s", TAG, level, msg)
end
function Log.Info(fmt, ...)
print(FormatMessage("INFO", fmt, ...))
end
function Log.Warn(fmt, ...)
print(FormatMessage("WARN", fmt, ...))
end
function Log.Error(fmt, ...)
print(FormatMessage("ERROR", fmt, ...))
end
return Log
+14
View File
@@ -0,0 +1,14 @@
---@type LuaCharacter
local M = UnLua.Class()
local Log = require("Framework.Log")
function M:ReceiveBeginPlay()
Log.Info("LuaCharacter:ReceiveBeginPlay()")
end
function M:ReceiveEndPlay(EndPlayReason)
Log.Info("LuaCharacter:ReceiveEndPlay(reason=%s)", tostring(EndPlayReason))
end
return M
+17
View File
@@ -0,0 +1,17 @@
---@type LuaGameInstance
local M = UnLua.Class()
local Bootstrap = require("Framework.Bootstrap")
local Log = require("Framework.Log")
function M:ReceiveInit()
Bootstrap.Init(self)
Log.Info("LuaGameInstance:ReceiveInit()")
end
function M:ReceiveShutdown()
Log.Info("LuaGameInstance:ReceiveShutdown()")
Bootstrap.Shutdown()
end
return M
+14
View File
@@ -0,0 +1,14 @@
---@type LuaGameModeBase
local M = UnLua.Class()
local Log = require("Framework.Log")
function M:ReceiveBeginPlay()
Log.Info("LuaGameMode:ReceiveBeginPlay()")
end
function M:ReceiveEndPlay(EndPlayReason)
Log.Info("LuaGameMode:ReceiveEndPlay(reason=%s)", tostring(EndPlayReason))
end
return M
@@ -0,0 +1,14 @@
---@type LuaPlayerController
local M = UnLua.Class()
local Log = require("Framework.Log")
function M:ReceiveBeginPlay()
Log.Info("LuaPlayerController:ReceiveBeginPlay()")
end
function M:ReceiveEndPlay(EndPlayReason)
Log.Info("LuaPlayerController:ReceiveEndPlay(reason=%s)", tostring(EndPlayReason))
end
return M
@@ -0,0 +1,44 @@
[CommonSettings]
SourcePath=Plugins/UnLua/Content/Localization/UnLua
DestinationPath=Plugins/UnLua/Content/Localization/UnLua
ManifestName=UnLua.manifest
ArchiveName=UnLua.archive
PortableObjectName=UnLua.po
ResourceName=UnLua.locres
NativeCulture=en
CulturesToGenerate=en
CulturesToGenerate=zh-Hans
;Gather text from source code
[GatherTextStep0]
CommandletClass=GatherTextFromSource
SearchDirectoryPaths=Plugins/UnLua/Source/
FileNameFilters=*.cpp
FileNameFilters=*.h
FileNameFilters=*.c
FileNameFilters=*.inl
FileNameFilters=*.mm
FileNameFilters=*.ini
ShouldGatherFromEditorOnlyData=false
;Write Manifest
[GatherTextStep1]
CommandletClass=GenerateGatherManifest
;Write Archives
[GatherTextStep2]
CommandletClass=GenerateGatherArchive
;Import localized PO files
[GatherTextStep3]
CommandletClass=InternationalizationExport
bImportLoc=true
;Write Localized Text Resource
[GatherTextStep4]
CommandletClass=GenerateTextLocalizationResource
;Export PO files
[GatherTextStep5]
CommandletClass=InternationalizationExport
bExportLoc=true
@@ -0,0 +1,36 @@
--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--
---@type ClassName
local M = UnLua.Class()
-- function M:Initialize(Initializer)
-- end
-- function M:UserConstructionScript()
-- end
-- function M:ReceiveBeginPlay()
-- end
-- function M:ReceiveEndPlay()
-- end
-- function M:ReceiveTick(DeltaSeconds)
-- end
-- function M:ReceiveAnyDamage(Damage, DamageType, InstigatedBy, DamageCauser)
-- end
-- function M:ReceiveActorBeginOverlap(OtherActor)
-- end
-- function M:ReceiveActorEndOverlap(OtherActor)
-- end
return M
@@ -0,0 +1,24 @@
--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--
---@type ClassName
local M = UnLua.Class()
-- function M:Initialize(Initializer)
-- end
-- function M:ReceiveBeginPlay()
-- end
-- function M:ReceiveEndPlay()
-- end
-- function M:ReceiveTick(DeltaSeconds)
-- end
return M
@@ -0,0 +1,27 @@
--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--
---@type ClassName
local M = UnLua.Class()
-- function M:Initialize(Initializer)
-- end
-- function M:BlueprintInitializeAnimation()
-- end
-- function M:BlueprintBeginPlay()
-- end
-- function M:BlueprintUpdateAnimation(DeltaTimeX)
-- end
-- function M:BlueprintPostEvaluateAnimation()
-- end
return M
@@ -0,0 +1,21 @@
--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--
---@type ClassName
local M = UnLua.Class()
-- function M:Received_NotifyBegin(MeshComp, Animation, TotalDuration)
-- end
-- function M:Received_NotifyTick(MeshComp, Animation, FrameDeltaTime)
-- end
-- function M:Received_NotifyEnd(MeshComp, Animation)
-- end
return M
@@ -0,0 +1,12 @@
--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--
---@type ClassName
local M = UnLua.Class()
return M
@@ -0,0 +1,24 @@
--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--
---@type ClassName
local M = UnLua.Class()
--function M:Initialize(Initializer)
--end
--function M:PreConstruct(IsDesignTime)
--end
-- function M:Construct()
-- end
--function M:Tick(MyGeometry, InDeltaTime)
--end
return M
@@ -0,0 +1,316 @@
---@class UnLua
local UnLua = {}
---Similar to "package.path" for lua module searching with UnLua loader. Used by FLuaEnv::LoadFromFileSystem.
UnLua.PackagePath = "Content/Script/?.lua;Plugins/UnLua/Content/Script/?.lua"
---Whether or not enable FText support at lua runtime which will no longer be treated as a string.
UnLua.FTextEnabled = false
---Define a lua class for binding.
---@param SuperClass string @[opt]
function UnLua.Class(SuperClass)
end
---Hot reload lua modules
---@param ModuleNames table @[opt]Specify a list of module names that need hot reloading. If this parameter is not passed, it will be obtained by default according to the file modification timestamp
function UnLua.HotReload(ModuleNames)
end
---Add or find a manual reference to specified UObject. This prevents the object from UE GC.
---@param Object UObject
---@return userdata @Proxy object of the reference. The reference of UObject will be removed when proxy object deleted by lua GC.
function UnLua.Ref(Object)
end
---Force remove all manual reference to specified UObject.
---@param Object UObject
function UnLua.Unref(Object)
end
_G.UnLua = UnLua
---@class TArray<TElement>
local TArray = {}
---Get the number of items in an array
---@return integer
function TArray:Length()
end
---Get the number of items in an array
---@return integer
function TArray:Num()
end
---Add item to array
---@param NewItem TElement @The item to look for
---@return integer @The index of the newly added item
function TArray:Add(NewItem)
end
---Add item to array (unique)
---@param NewItem TElement @The item to add to the array
---@return integer @The index of the newly added item, or INDEX_NONE if the item is already present in the array
function TArray:AddUnique(NewItem)
end
---Finds the index of the first instance of the item within the array
---@param ItemToFind TElement @The item to look for
---@return integer @The index the item was found at, or -1 if not found
function TArray:Find(ItemToFind)
end
---Insert item at the given index into the array.
---@param NewItem TElement @The item to insert into the array
---@param Index integer @The index at which to insert the item into the array
function TArray:Insert(NewItem, Index)
end
---Remove item at the given index from the array.
---@param IndexToRemove integer @The index into the array to remove from
function TArray:Remove(IndexToRemove)
end
---Remove all instances of item from array.
---@param Item TElement @The item to remove from the array
---@return boolean @True if one or more items were removed
function TArray:RemoveItem(Item)
end
---Clear the array, removes all content
function TArray:Clear()
end
---Reserve space for N elements
---@param Size integer @Size
---@return bool @whether the operation succeed
function TArray:Reserve(Size)
end
---Resize Array to specified size.
---@param Size integer @The new size of the array
function TArray:Resize(Size)
end
---Get address of the i'th element
---@param Index integer @the index
---return lightuserdata @the address of the i'th element
function TArray:GetData(Index)
end
---Given an array and an index, returns a copy of the item found at that index
---@param Index integer @The index in the array to get an item from
---@return any @A copy of the item stored at the index
function TArray:Get(Index)
end
---Given an array and an index, returns a reference of the item found at that index
---@param Index integer @The index in the array to get an item from
---@return TElement @A reference of the item stored at the index
function TArray:GetRef(Index)
end
---Given an array and an index, assigns the item to that array element
---@param Index integer @The index to assign the item to
---@param Item TElement @The item to assign to the index of the array
function TArray:Set(Index, Item)
end
---Swaps the elements at the specified positions
---If the specified positions are equal, invoking this method leaves the array unchanged
---@param FirstIndex integer @The index of one element to be swapped
---@param SecondIndex integer @The index of the other element to be swapped
function TArray:Swap(FirstIndex, SecondIndex)
end
---Shuffle (randomize) the elements
function TArray:Shuffle()
end
---Get the last valid index
---@return integer @The last valid index of the array
function TArray:LastIndex()
end
---Tests if IndexToTest is valid, i.e. greater than or equal to zero, and less than the number of elements in array.
---@param IndexToTest integer @The Index, that we want to test for being valid
---@return boolean @True if the Index is Valid, i.e. greater than or equal to zero, and less than the number of elements in array.
function TArray:IsValidIndex(IndexToTest)
end
---Returns true if the array contains the given item
---@param ItemToFind any @The item to look for
---@return boolean @True if the item was found within the array
function TArray:Contains(ItemToFind)
end
---Append an array to another array
---@param OtherArray TArray @The array to add
function TArray:Append(OtherArray)
end
---Get a lua table copy of this array.
---@return table
function TArray:ToTable()
end
---@type fun(ElementType:any):TArray
UE.TArray = TArray
---@class TMap<TKey,TValue>
local TMap = {}
---Determines the number of entries in map
---@return integer
function TMap:Length()
end
---Determines the number of entries in map
---@return integer
function TMap:Num()
end
---Adds a key and value to the map. If something already uses the provided key it will be overwritten with the new value.
---After calling Key is guaranteed to be associated with Value until a subsequent mutation of the Map.
---@param Key TKey @The key that will be used to look the value up
---@param Value TValue @The value to be retrieved later
function TMap:Add(Key, Value)
end
---Removes a key and its associated value from the map.
---@param Key any @The key that will be used to look the value up
---@return boolean @True if an item was removed (False indicates nothing in the map uses the provided key)
function TMap:Remove(Key)
end
---Finds the value associated with the provided Key
---@param Key any @The key that will be used to look the value up
---@return any @The value associated with the key
function TMap:Find(Key)
end
---Finds the value associated with the provided Key
---@param Key any @The key that will be used to look the value up
---@return any @The value associated with the key
function TMap:FindRef(Key)
end
---Clears all entries, resetting it to empty
function TMap:Clear()
end
---Outputs an array of all keys present in the map
---@return TArray @All keys present in the map
function TMap:Keys()
end
---Outputs an array of all values present in the map
---@return TArray @All values present in the map
function TMap:Values()
end
---Get a lua table copy of this map.
---@return table
function TMap:ToTable()
end
---@type fun(KeyType:any,ValueType:any):TMap
UE.TMap = TMap
---@class TSet<TElement>
local TSet = {}
---Get the number of items in set.
---@return integer
function TSet:Length()
end
---Get the number of items in set.
---@return integer
function TSet:Num()
end
---Adds item to set
---@param NewItem TElement @The item to add to the set
function TSet:Add(NewItem)
end
---Remove item from set
---@param Item TElement @The item to remove from the set
---@return boolean @True if an item was removed (False indicates no equivalent item was present)
function TSet:Remove(Item)
end
---Returns true if the set contains the given item.
---@param ItemToFind any @The item to look for
---@return boolean @True if the item was found within the set
function TSet:Contains(ItemToFind)
end
---Clear the set, removes all content.
function TSet:Clear()
end
---Outputs an Array containing copies of the entries of a Set.
---@return TArray @Array
function TSet:ToArray()
end
---Get a lua table copy of this set.
---@return table
function TSet:ToTable()
end
---@type fun(ElementType:any):TSet
UE.TSet = TSet
---@class UClass
local UClass = {}
---Load a class object
---@param Path string @path to the class
---@return UClass
function UClass.Load(Path)
end
---Test whether this class is a child of another class
---@param TargetClass UClass @target class
---@return boolean @true if this object is of the specified type.
function UClass:IsChildOf(TargetClass)
end
---Get default object of a class.
---@return UObject @class default obejct
function UClass:GetDefaultObject()
end
UE.UClass = UClass
---@class MulticastDelegate
local MulticastDelegate = {}
---Add a callback to the delegate
---@param Object UObject @receiver object
---@param Callback function @callback
function MulticastDelegate:Add(Object, Function)
end
---Remove a callback from the delegate
---@param Object UObject @receiver object
---@param Callback function @callback
function MulticastDelegate:Remove(Object, Function)
end
---Clear all callbacks for the delegate
function MulticastDelegate:Clear()
end
---Call all callbacks bound to the delegate
function MulticastDelegate:Broadcast()
end
---Detect if any callback bound to this delegate
---@return boolean
function MulticastDelegate:IsBound()
end
@@ -0,0 +1,17 @@
Date/Time,Word Count,zh-Hans
2022.03.17-11.26.16,101,101
2022.05.28-01.30.11,166,166
2022.06.07-12.00.37,183,183
2022.06.07-12.18.21,187,187
2022.06.07-12.23.19,321,321
2022.06.07-12.38.33,187,187
2022.06.07-12.40.09,515,515
2022.06.07-12.44.45,585,585
2022.06.07-13.04.33,515,515
2022.06.07-13.08.26,585,585
2022.06.07-13.27.43,599,599
2022.06.07-18.25.31,562,562
2022.06.07-19.09.46,606,606
2022.06.07-21.37.50,504,504
2022.06.07-22.44.41,568,568
2022.09.24-18.38.33,665,665
1 Date/Time Word Count zh-Hans
2 2022.03.17-11.26.16 101 101
3 2022.05.28-01.30.11 166 166
4 2022.06.07-12.00.37 183 183
5 2022.06.07-12.18.21 187 187
6 2022.06.07-12.23.19 321 321
7 2022.06.07-12.38.33 187 187
8 2022.06.07-12.40.09 515 515
9 2022.06.07-12.44.45 585 585
10 2022.06.07-13.04.33 515 515
11 2022.06.07-13.08.26 585 585
12 2022.06.07-13.27.43 599 599
13 2022.06.07-18.25.31 562 562
14 2022.06.07-19.09.46 606 606
15 2022.06.07-21.37.50 504 504
16 2022.06.07-22.44.41 568 568
17 2022.09.24-18.38.33 665 665
Whitespace-only changes.
@@ -0,0 +1,64 @@
local Input = UnLua.Input
local M = {}
local function MakeBinding(BindingClass, Args)
local Ret = BindingClass()
return Ret
end
local function MakeLuaFunction(Module, Prefix, Handler, No)
local Name = string.format("%s_%d", Prefix, No)
if not Module[Name] then
Module[Name] = Handler
return Name
end
return MakeLuaFunction(Module, Prefix, Handler, No + 1)
end
local SignatureFunctionNames = {
"EnhancedInputActionDigital",
"EnhancedInputActionAxis1D",
"EnhancedInputActionAxis2D",
"EnhancedInputActionAxis3D"
}
--- 为当前模块绑定操作输入响应
---@param Module table @需要绑定的lua模块
---@param InputAction string @绑定的操作资源路径,是个UInputAction
---@param TriggerEvent string @绑定的事件名称,参考ETriggerEvent下的命名
---@param Handler fun(Key:FKey) @事件响应回调函数
---@param Args table @[opt]扩展参数
function M.BindAction(Module, ActionPath, TriggerEvent, Handler, Args)
Args = Args or {}
Module.__UnLuaInputBindings = Module.__UnLuaInputBindings or {}
local InputAction = UE.UObject.Load(ActionPath)
if not InputAction then
return
end
local SignatureFunctionName = SignatureFunctionNames[InputAction.ValueType + 1]
local FunctionName = MakeLuaFunction(Module, string.format("UnLuaInput_%s_%s", InputAction:GetName(), TriggerEvent), Handler, 0)
local Bindings = Module.__UnLuaInputBindings
table.insert(Bindings, function(Manager, Class)
local BindingObject = Manager:GetOrAddBindingObject(Class, UE.UEnhancedInputActionDelegateBinding)
for _, OldBinding in pairs(BindingObject.InputActionDelegateBindings) do
if OldBinding.FunctionNameToBind == FunctionName then
-- PIE下这个蓝图可能已经绑定过了
Manager:Override(Class, SignatureFunctionName, FunctionName)
return
end
end
local Binding = MakeBinding(UE.FBlueprintEnhancedInputActionBinding, Args)
Binding.InputAction = InputAction
Binding.TriggerEvent = UE.ETriggerEvent[TriggerEvent]
Binding.FunctionNameToBind = FunctionName
BindingObject.InputActionDelegateBindings:Add(Binding)
Manager:Override(Class, SignatureFunctionName, FunctionName)
end)
end
return M
@@ -0,0 +1,629 @@
------------------------------------------
--- HotFix - 运行时HotFix支持 参考云风方案
--- 替换运行环境中的函数,保持upvalue和运行时的table
--- 为开发期设计,尽量替换。最差的结果就是重新启动
--- 原表改变,类型改变 后逻辑由业务保证正确
--- 基于lua 5.3,重定向require,使用env加载实现沙盒
--- 提供一系列回调注册,可以在hotfix前后做处理
------------------------------------------
-- 在Module中如果定义此标记,则对此module进行reload操作
-- local M = { HOT_RELOAD = true }
local HOT_RELOAD_MARK = "HOT_RELOAD"
local loaded_modules = setmetatable({}, { __mode = "v" })
local ignore_modules = {}
local config = {
debug = false,
script_root_path = UE.UUnLuaFunctionLibrary.GetScriptRootPath(),
ignore_modules = ignore_modules
}
local hook = {
module_loaded = nil
}
local M = {
config = config,
hook = hook
}
local dump = function(tbl, max_indent)
local rep = string.rep
local handled = {}
local function traverse(tbl, indent)
if not indent then indent = 0 end
if type(tbl) ~= "table" then return tostring(tbl) end
if(indent > max_indent) then return tostring(tbl) end
if handled[tbl] then
return ""
end
handled[tbl] = true
local ret = rep(" ", indent) .. "{\r\n"
indent = indent + 2
for k, v in pairs(tbl) do
ret = ret .. rep(" ", indent)
if type(k) == "number" then
ret = ret .. "[" .. k .. "] = "
elseif type(k) == "string" then
ret = ret .. k .. " = "
else
ret = ret .. tostring(k) .. " = "
end
if type(v) == "number" then
ret = ret .. v .. ",\r\n"
elseif type(v) == "string" then
ret = ret .. "\"" .. v .. "\",\r\n"
elseif type(v) == "table" then
ret = ret .. tostring(v) .. traverse(v, indent + 2) .. ",\r\n"
else
ret = ret .. "\"" .. tostring(v) .. "\",\r\n"
end
end
ret = ret .. rep(" ", indent - 2) .. "}"
return ret
end
if max_indent == nil then
max_indent = 64
end
return traverse(tbl)
end
local print = function(...)
if config.debug then
UnLua.Log("HotReload ", ...)
end
end
local table = table
local debug = debug
local pairs = pairs
local origin_require = require
local function safe_pairs(t)
local _next, _t, _nil = pairs(t)
local function safe_next(_t, i)
local ok, result, next_i, value = pcall(_next, _t, i)
if ok then
return result, next_i, value
else
return nil
end
end
return safe_next, _t, _nil
end
local function load_error_handler(err)
local msg = err .. "\n" .. debug.traceback()
UnLua.LogError(msg)
end
local function call_hook(name, ...)
local func = hook[name]
if not func then
return
end
local ok, result = pcall(func, ...)
if not ok then
print(string.format("calling hook function '%s' failed : %s", name, result))
end
end
--- 脚本加载的修改时间
---@type table<string, number>
local loaded_module_times = {}
local function get_last_modified_time(module_name)
local filename = config.script_root_path .. module_name:gsub("%.", "/") .. ".lua"
return UE.UUnLuaFunctionLibrary.GetFileLastModifiedTimestamp(filename)
end
local function make_sandbox()
local reloading
local loaded
local proxy = setmetatable({}, { __index = _G, __newindex = _G })
local env_mt = { __index = proxy, __newindex = proxy }
local function load(module_name)
local found, chunk
for i, searcher in ipairs(package.searchers) do
chunk = searcher(module_name)
if type(chunk) == "function" then
found = true
break
end
end
if not found then
return
end
local env = {}
setmetatable(env, env_mt)
debug.setupvalue(chunk, 1, env)
return chunk, env
end
local function require(module_name, ...)
-- https://github.com/lua/lua/blob/v5.4.0/loadlib.c#L680
-- https://github.com/lua/lua/blob/v5.3/loadlib.c#L617
-- lua5.4之后会返回2个值,这里保持一样的行为
if package.loaded[module_name] ~= nil then
return package.loaded[module_name], nil
end
local loaded = loaded_modules[module_name]
if loaded then
if package.loaded[module_name] == nil then
package.loaded[module_name] = loaded
end
return loaded, nil
end
local func, env = load(module_name)
if func then
local _, new_module = xpcall(func, load_error_handler, ...)
if loaded_modules[module_name] == nil then
loaded_modules[module_name] = new_module
package.loaded[module_name] = new_module
loaded_module_times[module_name] = get_last_modified_time(module_name)
call_hook("module_loaded", new_module, module_name, false)
return new_module, nil
end
else
return origin_require(module_name, ...)
end
return env, nil
end
local function enter(modules)
reloading = true
loaded = setmetatable({}, { __mode = "kv" })
for name, module in pairs(modules) do
loaded[name] = module
loaded[module] = name
end
end
local function exit()
reloading = false
loaded = setmetatable({}, { __mode = "kv" })
end
local function is_loaded(obj)
return loaded[obj] ~= nil
end
proxy.require = function(module_name, ...)
if reloading then
if loaded[module_name] ~= nil then
return loaded[module_name]
end
end
local ret = require(module_name, ...)
if reloading then
loaded[module_name] = ret
loaded[ret] = module_name
end
return ret
end
return {
enter = enter,
exit = exit,
load = load,
require = require,
is_loaded = is_loaded,
}
end
local sandbox = make_sandbox()
local function merge_objects(module_res)
for _, m in ipairs(module_res) do
assert(m.old_module)
for index, v in ipairs(m.values) do
for name, value_map in pairs(v) do
for old, new in pairs(value_map) do
if old == nil and not sandbox.is_loaded(new) then
m.old_module[name] = new
elseif type(new) == "table" and not sandbox.is_loaded(new) then
print("COPY", tostring(new), tostring(old))
for k, nv in pairs(new) do
old[k] = nv
end
elseif type(new) == "function" then
local i = 1
while true do
local name,v = debug.getupvalue(new, i)
if name == nil or name == "" then
break
end
local id = debug.upvalueid(new, i)
local uv = m.upvalue_map[id]
if uv then
print("SET UV :", tostring(new), name, tostring(uv.replaced_upvalue))
debug.setupvalue(new, i, uv.replaced_upvalue)
end
i = i + 1
end
end
end
end
end
end
end
--- 枚举出module中所有函数的upvalue,Lua在不同的闭包间访问相同的外部local变量时,使用的是同样的upvalue
---@param moudule table
local function collect_module_upvalues(moudule)
local function collect_function_upvalues(func, upvalues)
assert(type(func) == "function")
local i = 1
while true do
local name, value = debug.getupvalue(func, i)
if name == nil or name == "" then
break
else
if not name:find("^[_%w]") then
error("Invalid upvalue : " .. table.concat(path, "."))
end
if not upvalues[name] then
upvalues[name] = value
if type(value) == "function" then
collect_function_upvalues(value, upvalues)
end
end
end
i = i + 1
end
end
local ret = {}
for _, v in pairs(moudule) do
if type(v) == "function" then
collect_function_upvalues(v, ret)
end
end
return ret
end
local function collect_module_info(module)
local ret = {}
if sandbox.is_loaded(module) then
return ret
end
for k, v in pairs(module) do
if sandbox.is_loaded(v) then
elseif type(v) == "function" then
table.insert(ret, {name = k, value = v})
end
end
return ret
end
---@param new_module_info table
---@param old_module table
---@return table
local function match_module(new_module_info, old_module)
local ret = {}
for _, v in ipairs(new_module_info) do
local oldFun = rawget(old_module, v.name)
if oldFun and oldFun ~= v.value then
table.insert(ret, { [v.name] = { [oldFun] = v.value } } )
end
end
return ret
end
---@param value_info_map table
---@param old_upvalues table
---@return table
local function match_upvalues(value_info_map, old_upvalues)
local ret = {}
for index, v in ipairs(value_info_map) do
for name, value_map in pairs(v) do
for old, new in pairs(value_map) do
if type(new) == "function" then
local i = 1
while true do
local name, new_upvalue = debug.getupvalue(new, i)
if name == nil or name == "" then
break
end
local id = debug.upvalueid(new, i)
if not ret[id] then
local replaced_upvalue = nil
if old_upvalues[name] ~= nil then
replaced_upvalue = old_upvalues[name]
else
-- 新增的upvalue
print("ADD NEW UPVALUE : ", tostring(new), name, tostring(new_upvalue))
-- 解决新增的upvalue是当前module
if type(new_upvalue) == "table" or type(new_upvalue) == "function" and value_info_map[new_upvalue] ~= nil then
replaced_upvalue = value_info_map[new_upvalue]
else
replaced_upvalue = new_upvalue
end
end
if replaced_upvalue then
ret[id] = { replaced_upvalue = replaced_upvalue }
end
end
i = i + 1
end
end
end
end
end
return ret
end
local function update_global(value_map)
local running_state = coroutine.running()
local exclude = { [debug] = true, [coroutine] = true, [io] = true }
exclude[exclude] = true
exclude[M] = true
exclude[sandbox] = true
exclude[value_map] = true
exclude[package] = true
exclude[package.loaded] = true
exclude[loaded_modules] = true
local update_table
local function update_running_stack(co, level)
local info = debug.getinfo(co, level + 1, "f")
if info == nil then
return
end
local f = info.func
info = nil
update_table(f)
local i = 1
while true do
local name, v = debug.getlocal(co, level + 1, i)
if name == nil then
if i > 0 then
i = -1
else
break
end
end
local nv = value_map[v]
if nv then
debug.setlocal(co, level + 1, i, nv)
update_table(nv)
else
update_table(v)
end
if i > 0 then
i = i + 1
else
i = i - 1
end
end
return update_running_stack(co, level + 1)
end
function update_table(root)
if root == nil or exclude[root] then
return
end
-- print("update_table : ", dump(root, 2))
exclude[root] = true
local t = type(root)
if t == "table" then
local mt = getmetatable(root)
if mt then update_table(mt) end
local ReplaceK = {}
for key, value in safe_pairs(root) do
local nv = value_map[value]
if nv then
rawset(root, key, nv)
update_table(nv)
else
update_table(value)
end
nv = value_map[key]
if nv then
ReplaceK[key] = nv
end
end
for key, value in pairs(ReplaceK) do
root[key], root[value] = nil, root[key]
update_table(value)
end
elseif t == "userdata" then
local mt = getmetatable(root)
if mt then update_table(mt) end
local user_value = debug.getuservalue(root)
if user_value then
local nv = value_map[user_value]
if nv then
debug.setuservalue(root, user_value)
update_table(nv)
else
update_table(user_value)
end
end
elseif t == "function" then
local i = 1
while true do
local name, v = debug.getupvalue(root, i)
if name == nil then
break
else
local nv = value_map[v]
if nv then
update_table(nv)
else
update_table(v)
end
end
i=i+1
end
end
end
update_running_stack(running_state, 2)
update_table(_G)
update_table(debug.getregistry())
end
local function update_modules(old_modules, new_modules, new_envs)
print("HOT RELOAD START")
local result = {}
for i, old_module in ipairs(old_modules) do
local new_module = new_modules[i]
local new_env = new_envs[i]
if new_module[HOT_RELOAD_MARK] then
local moduleres = {
values = {},
old_module = old_module
}
table.insert(moduleres.values, { [new_module] = { [old_module] = new_module } } )
print("--------------Print ValueMap--------------")
print(dump(moduleres.values, 6))
result[i] = moduleres
else
local new_module_info = collect_module_info(new_module)
print("--------------Print NewModuleInfo--------------")
print(dump(new_module_info))
local old_module_upvalues = collect_module_upvalues(old_module)
print("--------------Print OldModuleUpValue--------------")
print(dump(old_module_upvalues, 6))
local moduleres = {
values = {},
upvalue_map = {},
old_module = old_module,
}
moduleres.values = match_module(new_module_info, old_module)
for k, v in pairs(new_module) do
if type(v) == "function" then
old_module[k] = v
end
if old_module[k] == nil then
old_module[k] = v
end
end
print("--------------Print ValueMap--------------")
print(dump(moduleres.values))
moduleres.upvalue_map = match_upvalues(moduleres.values, old_module_upvalues)
print("--------------Print UVMap--------------")
print(dump(moduleres.upvalue_map, 10))
result[i] = moduleres
end
end
merge_objects(result)
local all_value_maps = {}
for _, rv in ipairs(result) do
for _, v in ipairs(rv.values) do
for name, value_map in pairs(v) do
for key, value in pairs(value_map) do
all_value_maps[key] = value
end
end
end
end
print("--------------Print AllValueMap--------------")
print(dump(all_value_maps))
update_global(all_value_maps)
print("HOT RELOAD END")
end
---@param module_names table
local function reload_modules(module_names)
if not module_names or #module_names == 0 then
return
end
local tmp_modules = {}
for _, module_name in ipairs(module_names) do
if loaded_modules[module_name] then
tmp_modules[module_name] = loaded_modules[module_name]
end
end
sandbox.enter(tmp_modules)
local old_modules = {}
local new_modules = {}
local module_envs = {}
for _, module_name in ipairs(module_names) do
if loaded_modules[module_name] == nil then
sandbox.require(module_name)
else
local func, env = sandbox.load(module_name)
if func ~= nil then
local ok, new_module = xpcall(func, load_error_handler)
if not ok then
sandbox.exit()
return
end
if new_module then
for k, v in pairs(env) do
new_module[k] = v
end
else
new_module = env
end
old_modules[#old_modules+1] = loaded_modules[module_name]
new_modules[#new_modules+1] = new_module
module_envs[#module_envs+1] = env
call_hook("module_loaded", new_module, module_name, true)
else
sandbox.exit()
return
end
end
end
update_modules(old_modules, new_modules, module_envs)
sandbox.exit()
end
function M.reload(module_names)
if module_names then
reload_modules(module_names)
return
end
local modified_modules = {}
for module_name, time in pairs(loaded_module_times) do
if not ignore_modules[module_name] then
local current_time = get_last_modified_time(module_name)
if current_time ~= time then
modified_modules[#modified_modules + 1] = module_name
loaded_module_times[module_name] = current_time
end
end
end
print("modified modules:", dump(modified_modules))
if #modified_modules > 0 then
reload_modules(modified_modules)
end
end
M.require = sandbox.require
return M
@@ -0,0 +1,152 @@
local M = {}
local function GetBooleanArg(Args, Name, DefaultValue)
if Args[Name] == nil then
return DefaultValue
end
return not not Args[Name]
end
local function MakeBinding(BindingClass, Args)
local Ret = BindingClass()
Ret.bConsumeInput = GetBooleanArg(Args, "ConsumeInput", true)
Ret.bExecuteWhenPaused = GetBooleanArg(Args, "ExecuteWhenPaused", false)
Ret.bOverrideParentBinding = GetBooleanArg(Args, "OverrideParentBinding", true)
return Ret
end
local function MakeLuaFunction(Module, Prefix, Handler, No)
local Name = string.format("%s_%d", Prefix, No)
if not Module[Name] then
Module[Name] = Handler
return Name
end
return MakeLuaFunction(Module, Prefix, Handler, No + 1)
end
local Modifiers = { "Ctrl", "Alt", "Shift", "Cmd" }
local function GetModifierSuffix(Args)
local Array = { "" }
for _, Modifier in ipairs(Modifiers) do
if Args[Modifier] then
table.insert(Array, Modifier)
end
end
return table.concat(Array, "_")
end
--- 为当前模块绑定按键输入响应
---@param Module table @需要绑定的lua模块
---@param KeyName string @绑定的按键名称,参考EKeys下的命名
---@param KeyEvent string @绑定的事件名称,参考EInputEvent下的命名,不需要 “IE_” 前缀
---@param Handler fun(Key:FKey) @事件响应回调函数
---@param Args table @[opt]扩展参数 使用 Ctrl/Shift/Alt/Cmd = true 来控制组合键
function M.BindKey(Module, KeyName, KeyEvent, Handler, Args)
Args = Args or {}
Module.__UnLuaInputBindings = Module.__UnLuaInputBindings or {}
local ModifierSuffix = GetModifierSuffix(Args)
local FunctionName = MakeLuaFunction(Module, string.format("UnLuaInput_%s_%s%s", KeyName, KeyEvent, ModifierSuffix), Handler, 0)
local Bindings = Module.__UnLuaInputBindings
table.insert(Bindings, function(Manager, Class)
local BindingObject = Manager:GetOrAddBindingObject(Class, UE.UInputKeyDelegateBinding)
for _, OldBinding in pairs(BindingObject.InputKeyDelegateBindings) do
if OldBinding.FunctionNameToBind == FunctionName then
-- PIE下这个蓝图可能已经绑定过了
Manager:Override(Class, "InputAction", FunctionName)
return
end
end
local InputChord = UE.FInputChord()
InputChord.Key = UE.EKeys[KeyName]
InputChord.bShift = not not Args.Shift
InputChord.bCtrl = not not Args.Ctrl
InputChord.bAlt = not not Args.Alt
InputChord.bCmd = not not Args.Cmd
local Binding = MakeBinding(UE.FBlueprintInputKeyDelegateBinding, Args)
Binding.InputChord = InputChord
Binding.InputKeyEvent = UE.EInputEvent["IE_" .. KeyEvent]
Binding.FunctionNameToBind = FunctionName
BindingObject.InputKeyDelegateBindings:Add(Binding)
Manager:Override(Class, "InputAction", FunctionName)
end)
end
--- 为当前模块绑定操作输入响应
---@param Module table @需要绑定的lua模块
---@param ActionName string @绑定的操作名称,对应 “项目设置->输入” 中设置的命名
---@param KeyEvent string @绑定的事件名称,参考EInputEvent下的命名,不需要 “IE_” 前缀
---@param Handler fun(Key:FKey) @事件响应回调函数
---@param Args table @[opt]扩展参数
function M.BindAction(Module, ActionName, KeyEvent, Handler, Args)
Args = Args or {}
Module.__UnLuaInputBindings = Module.__UnLuaInputBindings or {}
local FunctionName = MakeLuaFunction(Module, string.format("UnLuaInput_%s_%s", ActionName, KeyEvent), Handler, 0)
local Bindings = Module.__UnLuaInputBindings
table.insert(Bindings, function(Manager, Class)
local BindingObject = Manager:GetOrAddBindingObject(Class, UE.UInputActionDelegateBinding)
for _, OldBinding in pairs(BindingObject.InputActionDelegateBindings) do
if OldBinding.FunctionNameToBind == FunctionName then
-- PIE下这个蓝图可能已经绑定过了
Manager:Override(Class, "InputAction", FunctionName)
return
end
end
local Binding = MakeBinding(UE.FBlueprintInputActionDelegateBinding, Args)
Binding.InputActionName = ActionName
Binding.InputKeyEvent = UE.EInputEvent["IE_" .. KeyEvent]
Binding.FunctionNameToBind = FunctionName
BindingObject.InputActionDelegateBindings:Add(Binding)
Manager:Override(Class, "InputAction", FunctionName)
end)
end
--- 为当前模块绑定轴输入响应
---@param Module table @需要绑定的lua模块
---@param AxisName string @绑定的轴名称,对应 “项目设置->输入” 中设置的命名
---@param Handler fun(AxisValue:number) @事件响应回调函数
---@param Args table @[opt]扩展参数
function M.BindAxis(Module, AxisName, Handler, Args)
Args = Args or {}
Module.__UnLuaInputBindings = Module.__UnLuaInputBindings or {}
local FunctionName = MakeLuaFunction(Module, string.format("UnLuaInput_%s", AxisName), Handler, 0)
local Bindings = Module.__UnLuaInputBindings
table.insert(Bindings, function(Manager, Class)
local BindingObject = Manager:GetOrAddBindingObject(Class, UE.UInputAxisDelegateBinding)
for _, OldBinding in pairs(BindingObject.InputAxisDelegateBindings) do
if OldBinding.FunctionNameToBind == FunctionName then
-- PIE下这个蓝图可能已经绑定过了
Manager:Override(Class, "InputAxis", FunctionName)
return
end
end
local Binding = MakeBinding(UE.FBlueprintInputAxisDelegateBinding, Args)
Binding.InputAxisName = AxisName
Binding.FunctionNameToBind = FunctionName
BindingObject.InputAxisDelegateBindings:Add(Binding)
Manager:Override(Class, "InputAxis", FunctionName)
end)
end
function M.PerformBindings(Module, Manager, Class)
local Bindings = Module.__UnLuaInputBindings
if not Bindings then
return
end
for _, Binding in ipairs(Bindings) do
xpcall(Binding, function(Error)
UnLua.LogError(Error .. "\n" .. debug.traceback())
end, Manager, Class)
end
end
return M
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

+76
View File
@@ -0,0 +1,76 @@
# Tencent is pleased to support the open source community by making UnLua available.
#
# Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the MIT License (the "License");
# you may not use this file except in compliance with the License. You may obtain a copy of the License at
#
# http://opensource.org/licenses/MIT
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
cmake_minimum_required(VERSION 2.8)
project(Lua)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
if(NOT LUA_VERSION)
set(LUA_VERSION "lua-5.4.3")
endif()
set(LUA_IDSIZE 256 CACHE STRING "gives the maximum size for the description of the source of a function in debug information.")
set(LUA_SRC_PATH ${LUA_VERSION}/src)
aux_source_directory(${LUA_SRC_PATH} LUA_CORE)
list(REMOVE_ITEM LUA_CORE "${LUA_SRC_PATH}/onelua.c")
add_definitions(-DLUA_IDSIZE=${LUA_IDSIZE})
if(LUA_COMPILE_AS_CPP)
set_source_files_properties(${LUA_CORE} PROPERTIES LANGUAGE CXX)
endif()
if(WIN32 AND NOT CYGWIN)
add_library(Lua SHARED
${LUA_CORE}
)
elseif(APPLE)
if(IOS)
add_definitions(-DLUA_NO_OS_EXECUTE)
add_library(Lua STATIC
${LUA_CORE}
)
else()
set(CMAKE_MACOSX_RPATH 1)
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/libLua")
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.10)
add_definitions(-DLUA_USE_MACOSX)
add_library(Lua SHARED
${LUA_CORE}
)
endif()
elseif(PS5)
add_definitions(-DLUA_NO_OS_EXECUTE)
add_definitions(-DLUA_NO_OS_TMPNAME)
add_definitions(-DLUA_NO_IO_TMPFILE)
add_library(Lua STATIC
${LUA_CORE}
)
target_include_directories(Lua SYSTEM
PRIVATE ${SCE_PROSPERO_SDK_DIR}/target/include
PRIVATE ${SCE_PROSPERO_SDK_DIR}/target/include_common
PRIVATE ${LUA_SRC_PATH}/../src-ps5
)
else()
add_library(Lua STATIC
${LUA_CORE}
)
target_compile_options(Lua PRIVATE -fPIC)
endif()
if(WIN32 AND NOT CYGWIN)
target_compile_definitions(Lua PRIVATE LUA_BUILD_AS_DLL)
endif()
+493
View File
@@ -0,0 +1,493 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
#if UE_5_0_OR_LATER
using EpicGames.Core;
#else
using Tools.DotNETCommon;
#endif
using UnrealBuildTool;
public class Lua : ModuleRules
{
public Lua(ReadOnlyTargetRules Target) : base(Target)
{
Type = ModuleType.External;
#if UE_5_6_OR_LATER
CppCompileWarningSettings.UndefinedIdentifierWarningLevel = WarningLevel.Off;
#elif UE_5_5_OR_LATER
UndefinedIdentifierWarningLevel = WarningLevel.Off;
#else
bEnableUndefinedIdentifierWarnings = false;
#endif
#if UE_5_6_OR_LATER
CppCompileWarningSettings.ShadowVariableWarningLevel = WarningLevel.Off;
#else
ShadowVariableWarningLevel = WarningLevel.Off;
#endif
m_LuaVersion = GetLuaVersion();
m_Config = GetConfigName();
m_LibName = GetLibraryName();
m_BuildSystem = GetBuildSystem();
m_CompileAsCpp = ShouldCompileAsCpp();
m_LibDirName = string.Format("lib-{0}", m_CompileAsCpp ? "cpp" : "c");
m_LuaDirName = m_LuaVersion;
PublicIncludePaths.Add(Path.Combine(ModuleDirectory, m_LuaDirName, "src"));
var buildMethodName = "BuildFor" + Target.Platform;
var buildMethod = GetType().GetMethod(buildMethodName, BindingFlags.Instance | BindingFlags.NonPublic);
if (buildMethod == null)
throw new NotSupportedException(buildMethodName);
buildMethod.Invoke(this, Array.Empty<object>());
}
#region Build for Platforms
private void BuildForWin64()
{
var dllPath = GetLibraryPath();
var libPath = Path.ChangeExtension(dllPath, ".lib");
var pdbPath = Path.ChangeExtension(dllPath, ".pdb");
var dirPath = Path.GetDirectoryName(dllPath);
var isDebug = m_Config == "Debug";
var dstFiles = new List<string> { dllPath, libPath };
if (isDebug)
dstFiles.Add(pdbPath);
if (!dstFiles.All(File.Exists))
{
var buildDir = CMake();
CopyDirectory(Path.Combine(buildDir, m_Config), dirPath);
}
PublicDefinitions.Add("LUA_BUILD_AS_DLL");
PublicDelayLoadDLLs.Add(m_LibName);
PublicAdditionalLibraries.Add(libPath);
SetupForRuntimeDependency(dllPath, "Win64");
if (isDebug)
SetupForRuntimeDependency(pdbPath, "Win64");
}
private void BuildForAndroid()
{
var ndkRoot = Environment.GetEnvironmentVariable("NDKROOT");
if (ndkRoot == null)
throw new BuildException("can't find NDKROOT");
var toolchain = GetAndroidToolChain();
var ndkApiLevel = toolchain.GetNdkApiLevelInt(21);
Console.WriteLine("toolchain.GetNdkApiLevelInt=", ndkApiLevel);
var abiNames = new[] { "armeabi-v7a", "arm64-v8a", "x86_64" };
foreach (var abiName in abiNames)
{
var libFile = GetLibraryPath(abiName);
PublicAdditionalLibraries.Add(libFile);
if (File.Exists(libFile))
continue;
EnsureDirectoryExists(libFile);
var args = new Dictionary<string, string>
{
{ "CMAKE_TOOLCHAIN_FILE", Path.Combine(ndkRoot, "build/cmake/android.toolchain.cmake") },
{ "ANDROID_ABI", abiName },
{ "ANDROID_PLATFORM", "android-" + ndkApiLevel }
};
var buildDir = CMake(args);
var buildFile = Path.Combine(buildDir, m_LibName);
File.Copy(buildFile, libFile, true);
}
}
private IAndroidToolChain GetAndroidToolChain()
{
#if UE_5_2_OR_LATER
var ueBuildPlatformType = Assembly.GetAssembly(typeof(IAndroidToolChain)).GetType("UnrealBuildTool.UEBuildPlatform");
var getBuildPlatformMethod = ueBuildPlatformType.GetMethod("GetBuildPlatform", BindingFlags.Static | BindingFlags.Public);
var androidBuildPlatform = getBuildPlatformMethod.Invoke(null, new object[] { UnrealTargetPlatform.Android });
var createTempToolChainForProjectMethod = androidBuildPlatform.GetType().GetMethod("CreateTempToolChainForProject");
var toolchain = (IAndroidToolChain)createTempToolChainForProjectMethod.Invoke(androidBuildPlatform, new object[] { Target.ProjectFile });
#else
var toolchain = AndroidExports.CreateToolChain(Target.ProjectFile);
#endif
return toolchain;
}
private void BuildForLinux()
{
var libFile = GetLibraryPath();
PublicAdditionalLibraries.Add(libFile);
if (File.Exists(libFile))
return;
var env = Environment.GetEnvironmentVariable("LINUX_MULTIARCH_ROOT");
if (string.IsNullOrEmpty(env))
throw new BuildException("LINUX_MULTIARCH_ROOT environment variable needed.");
EnsureDirectoryExists(libFile);
var sysName = "x86_64-unknown-linux-gnu";
var sysRoot = Path.Combine(env, sysName);
var clangPath = Path.Combine(env, sysName, @"bin\clang.exe");
var clangPlusPlusPath = Path.Combine(env, sysName, @"bin\clang++.exe");
var args = new Dictionary<string, string>
{
{ "CMAKE_SYSROOT", sysRoot },
{ "CMAKE_SYSTEM_NAME", "Linux" },
{ "CMAKE_C_COMPILER_TARGET", sysName },
{ "CMAKE_C_COMPILER:PATH", clangPath },
{ "CMAKE_CXX_COMPILER:PATH", clangPlusPlusPath },
{ "CMAKE_CXX_COMPILER_TARGET", sysName },
};
var buildDir = CMake(args);
var buildFile = Path.Combine(buildDir, m_LibName);
File.Copy(buildFile, libFile, true);
}
private void BuildForLinuxAArch64()
{
var libFile = GetLibraryPath();
PublicAdditionalLibraries.Add(libFile);
if (File.Exists(libFile))
return;
var env = Environment.GetEnvironmentVariable("LINUX_MULTIARCH_ROOT");
if (string.IsNullOrEmpty(env))
throw new BuildException("LINUX_MULTIARCH_ROOT environment variable needed.");
EnsureDirectoryExists(libFile);
var sysName = "aarch64-unknown-linux-gnueabi";
var sysRoot = Path.Combine(env, sysName);
var clangPath = Path.Combine(env, sysName, @"bin\clang.exe");
var clangPlusPlusPath = Path.Combine(env, sysName, @"bin\clang++.exe");
var args = new Dictionary<string, string>
{
{ "CMAKE_SYSROOT", sysRoot },
{ "CMAKE_SYSTEM_NAME", "Linux" },
{ "CMAKE_C_COMPILER_TARGET", sysName },
{ "CMAKE_C_COMPILER:PATH", clangPath },
{ "CMAKE_CXX_COMPILER:PATH", clangPlusPlusPath },
{ "CMAKE_CXX_COMPILER_TARGET", sysName },
};
var buildDir = CMake(args);
var buildFile = Path.Combine(buildDir, m_LibName);
File.Copy(buildFile, libFile, true);
}
private void BuildForMac()
{
#if UE_5_2_OR_LATER
var abiName = Target.Architecture.ToString();
#else
var abiName = Target.Architecture;
#endif
var libFile = GetLibraryPath(abiName);
if (!File.Exists(libFile))
{
EnsureDirectoryExists(libFile);
var args = new Dictionary<string, string>
{
{ "CMAKE_OSX_ARCHITECTURES", abiName }
};
var buildDir = CMake(args);
var buildFile = Path.Combine(buildDir, m_LibName);
File.Copy(buildFile, libFile, true);
}
PublicDefinitions.Add("LUA_USE_MACOSX");
PublicAdditionalLibraries.Add(libFile);
RuntimeDependencies.Add(libFile);
}
private void BuildForIOS()
{
var libFile = GetLibraryPath("arm64");
if (!File.Exists(libFile))
{
var args = new Dictionary<string, string>
{
{ "CMAKE_TOOLCHAIN_FILE", Path.Combine(ModuleDirectory, "toolchain/ios.toolchain.cmake") },
{ "PLATFORM", "OS64" }
};
var buildDir = CMake(args);
var buildFile = Path.Combine(buildDir, m_Config + "-iphoneos", m_LibName);
EnsureDirectoryExists(libFile);
File.Copy(buildFile, libFile, true);
}
PublicAdditionalLibraries.Add(libFile);
}
private void BuildForPS5()
{
var libFile = GetLibraryPath();
PublicAdditionalLibraries.Add(libFile);
PublicIncludePaths.Add(Path.Combine(ModuleDirectory, m_LuaDirName, "src-ps5"));
if (File.Exists(libFile))
return;
var sceRootDir = Environment.GetEnvironmentVariable("SCE_ROOT_DIR");
if (string.IsNullOrEmpty(sceRootDir))
throw new BuildException("SCE_ROOT_DIR environment variable needed.");
var sceSdkDir = Environment.GetEnvironmentVariable("SCE_PROSPERO_SDK_DIR");
if (string.IsNullOrEmpty(sceSdkDir))
throw new BuildException("SCE_PROSPERO_SDK_DIR environment variable needed.");
EnsureDirectoryExists(libFile);
var sysRoot = Path.Combine(sceSdkDir, @"target");
var clangPath = Path.Combine(sceSdkDir, @"host_tools/bin/prospero-clang.exe");
var clangPlusPlusPath = Path.Combine(sceSdkDir, @"host_tools/bin/prospero-clang.exe");
var arPath = Path.Combine(sceSdkDir, @"host_tools/bin/prospero-llvm-ar.exe");
var args = new Dictionary<string, string>
{
{ "CMAKE_TOOLCHAIN_FILE", Path.Combine(sceRootDir, @"Prospero\Tools\CMake\PS5.cmake") },
{ "PS5", "1" }
};
var buildDir = CMake(args);
var buildFile = Path.Combine(buildDir, m_Config, m_LibName);
File.Copy(buildFile, libFile, true);
}
#endregion
private string CMake(Dictionary<string, string> extraArgs = null)
{
if (extraArgs == null)
extraArgs = new Dictionary<string, string>();
Console.WriteLine("generating {0} library with cmake...", m_LuaDirName);
var osPlatform = Environment.OSVersion.Platform;
if (osPlatform == PlatformID.Win32NT)
{
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
WorkingDirectory = ModuleDirectory,
RedirectStandardInput = true,
UseShellExecute = false
};
var process = Process.Start(startInfo);
using (var writer = process.StandardInput)
{
var buildDir = string.Format("\"{0}/build\"", m_LuaDirName);
writer.WriteLine("rmdir /s /q {0} &mkdir {0} &pushd {0}", buildDir);
if (string.IsNullOrEmpty(m_BuildSystem))
writer.Write("cmake ../.. ");
else
writer.Write("cmake -G \"{0}\" ../.. ", m_BuildSystem);
var args = new Dictionary<string, string>
{
{ "LUA_VERSION", m_LuaVersion },
{ "LUA_COMPILE_AS_CPP", m_CompileAsCpp ? "1" : "0" },
};
foreach (var arg in args)
writer.Write(" -D{0}=\"{1}\"", arg.Key, arg.Value);
foreach (var arg in extraArgs)
writer.Write(" -D{0}=\"{1}\"", arg.Key, arg.Value);
writer.WriteLine();
writer.WriteLine("popd");
writer.WriteLine("cmake --build {0}/build --config {1}", m_LuaDirName, m_Config);
}
process.WaitForExit();
return Path.Combine(ModuleDirectory, m_LuaDirName, "build");
}
if (osPlatform == PlatformID.Unix || osPlatform == PlatformID.MacOSX)
{
var startInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
WorkingDirectory = ModuleDirectory,
RedirectStandardInput = true,
UseShellExecute = false
};
var process = Process.Start(startInfo);
using (var writer = process.StandardInput)
{
var buildDir = string.Format("\"{0}/build\"", m_LuaDirName);
writer.WriteLine("rm -rf {0} &&mkdir {0} &&cd {0}", buildDir);
writer.Write("cmake -G \"{0}\" ../.. ", m_BuildSystem);
var args = new Dictionary<string, string>
{
{ "LUA_VERSION", m_LuaVersion },
{ "LUA_COMPILE_AS_CPP", m_CompileAsCpp ? "1" : "0" },
};
foreach (var arg in args)
writer.Write(" -D{0}={1}", arg.Key, arg.Value);
foreach (var arg in extraArgs)
writer.Write(" -D{0}={1}", arg.Key, arg.Value);
writer.WriteLine();
writer.WriteLine("cd ../..");
writer.WriteLine("cmake --build {0}/build --config {1}", m_LuaDirName, m_Config);
}
process.WaitForExit();
return Path.Combine(ModuleDirectory, m_LuaDirName, "build");
}
throw new NotSupportedException();
}
private static void CopyDirectory(string srcDir, string dstDir)
{
var dir = new DirectoryInfo(srcDir);
if (!dir.Exists)
throw new DirectoryNotFoundException(dir.FullName);
var dirs = dir.GetDirectories();
Directory.CreateDirectory(dstDir);
foreach (var file in dir.GetFiles())
{
var targetFilePath = Path.Combine(dstDir, file.Name);
file.CopyTo(targetFilePath, true);
}
foreach (var subDir in dirs)
{
var newDstDir = Path.Combine(dstDir, subDir.Name);
CopyDirectory(subDir.FullName, newDstDir);
}
}
private bool ShouldCompileAsCpp()
{
var projectDir = Target.ProjectFile.Directory;
var configFilePath = projectDir + "/Config/DefaultUnLuaEditor.ini";
var configFileReference = new FileReference(configFilePath);
var configFile = FileReference.Exists(configFileReference)
? new ConfigFile(configFileReference)
: new ConfigFile();
var config = new ConfigHierarchy(new[] { configFile });
const string section = "/Script/UnLuaEditor.UnLuaEditorSettings";
bool flag;
if (config.GetBool(section, "bLuaCompileAsCpp", out flag))
return flag;
return false;
}
private string GetLuaVersion()
{
var projectDir = Target.ProjectFile.Directory;
var configFilePath = projectDir + "/Config/DefaultUnLuaEditor.ini";
var configFileReference = new FileReference(configFilePath);
var configFile = FileReference.Exists(configFileReference)
? new ConfigFile(configFileReference)
: new ConfigFile();
var config = new ConfigHierarchy(new[] { configFile });
const string section = "/Script/UnLuaEditor.UnLuaEditorSettings";
string version;
if (config.GetString(section, "LuaVersion", out version))
return version;
return "lua-5.4.3";
}
private void EnsureDirectoryExists(string fileName)
{
var dirName = Path.GetDirectoryName(fileName);
if (!Directory.Exists(dirName))
Directory.CreateDirectory(dirName);
}
private string GetLibraryName()
{
if (Target.Platform == UnrealTargetPlatform.Win64)
return "Lua.dll";
if (Target.Platform == UnrealTargetPlatform.Mac)
return "libLua.dylib";
return "libLua.a";
}
private string GetLibraryPath(string architecture = null)
{
if (architecture == null)
architecture = string.Empty;
return Path.Combine(ModuleDirectory, m_LuaDirName, m_LibDirName, Target.Platform.ToString(), architecture, m_Config, m_LibName);
}
private string GetConfigName()
{
if (Target.Configuration == UnrealTargetConfiguration.Debug
|| Target.Configuration == UnrealTargetConfiguration.DebugGame)
return "Debug";
return "Release";
}
private string GetBuildSystem()
{
var osPlatform = Environment.OSVersion.Platform;
if (osPlatform == PlatformID.Win32NT)
{
if (Target.Platform.IsInGroup(UnrealPlatformGroup.Linux))
return "Ninja";
if (Target.Platform.IsInGroup(UnrealPlatformGroup.Android))
return "Ninja";
if (Target.Platform.IsInGroup(UnrealPlatformGroup.Windows))
{
#if !UE_5_4_OR_LATER
if (Target.WindowsPlatform.Compiler == WindowsCompiler.VisualStudio2019)
return "Visual Studio 16 2019";
#endif
#if UE_4_27_OR_LATER
if (Target.WindowsPlatform.Compiler == WindowsCompiler.VisualStudio2022)
return "Visual Studio 17 2022";
#endif
}
}
if (osPlatform == PlatformID.Unix)
{
if (Target.Platform.IsInGroup(UnrealPlatformGroup.IOS))
return "Xcode";
return "Unix Makefiles";
}
return null;
}
private void SetupForRuntimeDependency(string fullPath, string platform)
{
if (!File.Exists(fullPath))
return;
var fileName = Path.GetFileName(fullPath);
var dstPath = Path.Combine("$(ProjectDir)", "Binaries", platform, fileName);
RuntimeDependencies.Add(dstPath, fullPath);
}
private readonly string m_LuaVersion;
private readonly string m_Config;
private readonly string m_LibName;
private readonly string m_LibDirName;
private readonly string m_LuaDirName;
private readonly string m_BuildSystem;
private readonly bool m_CompileAsCpp;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
#pragma once
#ifndef _PS5_SIGNAL
#define _PS5_SIGNAL
#endif
#include <sys/signal.h>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,49 @@
/*
** $Id: lapi.h $
** Auxiliary functions from Lua API
** See Copyright Notice in lua.h
*/
#ifndef lapi_h
#define lapi_h
#include "llimits.h"
#include "lstate.h"
/* Increments 'L->top', checking for stack overflows */
#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \
"stack overflow");}
/*
** If a call returns too many multiple returns, the callee may not have
** stack space to accommodate all results. In this case, this macro
** increases its stack space ('L->ci->top').
*/
#define adjustresults(L,nres) \
{ if ((nres) <= LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
/* Ensure the stack has at least 'n' elements */
#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \
"not enough elements in the stack")
/*
** To reduce the overhead of returning from C functions, the presence of
** to-be-closed variables in these functions is coded in the CallInfo's
** field 'nresults', in a way that functions with no to-be-closed variables
** with zero, one, or "all" wanted results have no overhead. Functions
** with other number of wanted results, as well as functions with
** variables to be closed, have an extra check.
*/
#define hastocloseCfunc(n) ((n) < LUA_MULTRET)
/* Map [-1, inf) (range of 'nresults') into (-inf, -2] */
#define codeNresults(n) (-(n) - 3)
#define decodeNresults(n) (-(n) - 3)
#endif
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,293 @@
/*
** $Id: lauxlib.h $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#ifndef lauxlib_h
#define lauxlib_h
#include <stddef.h>
#include <stdio.h>
#include "luaconf.h"
#include "lua.h"
/* global table */
#define LUA_GNAME "_G"
typedef struct luaL_Buffer luaL_Buffer;
/* extra error code for 'luaL_loadfilex' */
#define LUA_ERRFILE (LUA_ERRERR+1)
/* key, in the registry, for table of loaded modules */
#define LUA_LOADED_TABLE "_LOADED"
/* key, in the registry, for table of preloaded loaders */
#define LUA_PRELOAD_TABLE "_PRELOAD"
typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;
#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number))
LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz);
#define luaL_checkversion(L) \
luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES)
LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
LUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname);
LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
size_t *l);
LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
const char *def, size_t *l);
LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
lua_Integer def);
LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);
LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname);
LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname);
LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
LUALIB_API void (luaL_where) (lua_State *L, int lvl);
LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,
const char *const lst[]);
LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
/* predefined references */
#define LUA_NOREF (-2)
#define LUA_REFNIL (-1)
LUALIB_API int (luaL_ref) (lua_State *L, int t);
LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename,
const char *mode);
#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL)
LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
const char *name, const char *mode);
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
LUALIB_API lua_State *(luaL_newstate) (void);
LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
const char *p, const char *r);
LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s,
const char *p, const char *r);
LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);
LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
const char *msg, int level);
LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
lua_CFunction openf, int glb);
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
#define luaL_newlibtable(L,l) \
lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
#define luaL_newlib(L,l) \
(luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
#define luaL_argcheck(L, cond,arg,extramsg) \
((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg))))
#define luaL_argexpected(L,cond,arg,tname) \
((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname))))
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
#define luaL_dofile(L, fn) \
(luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_dostring(L, s) \
(luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
/* push the value used to represent failure/error */
#define luaL_pushfail(L) lua_pushnil(L)
/*
** Internal assertions for in-house debugging
*/
#if !defined(lua_assert)
#if defined LUAI_ASSERT
#include <assert.h>
#define lua_assert(c) assert(c)
#else
#define lua_assert(c) ((void)0)
#endif
#endif
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
struct luaL_Buffer {
char *b; /* buffer address */
size_t size; /* buffer size */
size_t n; /* number of characters in buffer */
lua_State *L;
union {
LUAI_MAXALIGN; /* ensure maximum alignment for buffer */
char b[LUAL_BUFFERSIZE]; /* initial buffer */
} init;
};
#define luaL_bufflen(bf) ((bf)->n)
#define luaL_buffaddr(bf) ((bf)->b)
#define luaL_addchar(B,c) \
((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \
((B)->b[(B)->n++] = (c)))
#define luaL_addsize(B,s) ((B)->n += (s))
#define luaL_buffsub(B,s) ((B)->n -= (s))
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);
LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);
#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
/* }====================================================== */
/*
** {======================================================
** File handles for IO library
** =======================================================
*/
/*
** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and
** initial structure 'luaL_Stream' (it may contain other fields
** after that initial structure).
*/
#define LUA_FILEHANDLE "FILE*"
typedef struct luaL_Stream {
FILE *f; /* stream (NULL for incompletely created streams) */
lua_CFunction closef; /* to close stream (NULL for closed streams) */
} luaL_Stream;
/* }====================================================== */
/*
** {==================================================================
** "Abstraction Layer" for basic report of messages and errors
** ===================================================================
*/
/* print a string */
#if !defined(lua_writestring)
#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
#endif
/* print a newline and flush the output */
#if !defined(lua_writeline)
#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout))
#endif
/* print an error message */
#if !defined(lua_writestringerror)
#define lua_writestringerror(s,p) \
(fprintf(stderr, (s), (p)), fflush(stderr))
#endif
/* }================================================================== */
/*
** {============================================================
** Compatibility with deprecated conversions
** =============================================================
*/
#if defined(LUA_COMPAT_APIINTCASTS)
#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a))
#define luaL_optunsigned(L,a,d) \
((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))
#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
#endif
/* }============================================================ */
#endif
@@ -0,0 +1,528 @@
/*
** $Id: lbaselib.c $
** Basic library
** See Copyright Notice in lua.h
*/
#define lbaselib_c
#define LUA_LIB
#include "lprefix.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
static int luaB_print (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
int i;
for (i = 1; i <= n; i++) { /* for each argument */
size_t l;
const char *s = luaL_tolstring(L, i, &l); /* convert it to string */
if (i > 1) /* not the first element? */
lua_writestring("\t", 1); /* add a tab before it */
lua_writestring(s, l); /* print it */
lua_pop(L, 1); /* pop result */
}
lua_writeline();
return 0;
}
/*
** Creates a warning with all given arguments.
** Check first for errors; otherwise an error may interrupt
** the composition of a warning, leaving it unfinished.
*/
static int luaB_warn (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
int i;
luaL_checkstring(L, 1); /* at least one argument */
for (i = 2; i <= n; i++)
luaL_checkstring(L, i); /* make sure all arguments are strings */
for (i = 1; i < n; i++) /* compose warning */
lua_warning(L, lua_tostring(L, i), 1);
lua_warning(L, lua_tostring(L, n), 0); /* close warning */
return 0;
}
#define SPACECHARS " \f\n\r\t\v"
static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
lua_Unsigned n = 0;
int neg = 0;
s += strspn(s, SPACECHARS); /* skip initial spaces */
if (*s == '-') { s++; neg = 1; } /* handle sign */
else if (*s == '+') s++;
if (!isalnum((unsigned char)*s)) /* no digit? */
return NULL;
do {
int digit = (isdigit((unsigned char)*s)) ? *s - '0'
: (toupper((unsigned char)*s) - 'A') + 10;
if (digit >= base) return NULL; /* invalid numeral */
n = n * base + digit;
s++;
} while (isalnum((unsigned char)*s));
s += strspn(s, SPACECHARS); /* skip trailing spaces */
*pn = (lua_Integer)((neg) ? (0u - n) : n);
return s;
}
static int luaB_tonumber (lua_State *L) {
if (lua_isnoneornil(L, 2)) { /* standard conversion? */
if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */
lua_settop(L, 1); /* yes; return it */
return 1;
}
else {
size_t l;
const char *s = lua_tolstring(L, 1, &l);
if (s != NULL && lua_stringtonumber(L, s) == l + 1)
return 1; /* successful conversion to number */
/* else not a number */
luaL_checkany(L, 1); /* (but there must be some parameter) */
}
}
else {
size_t l;
const char *s;
lua_Integer n = 0; /* to avoid warnings */
lua_Integer base = luaL_checkinteger(L, 2);
luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */
s = lua_tolstring(L, 1, &l);
luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
if (b_str2int(s, (int)base, &n) == s + l) {
lua_pushinteger(L, n);
return 1;
} /* else not a number */
} /* else not a number */
luaL_pushfail(L); /* not a number */
return 1;
}
static int luaB_error (lua_State *L) {
int level = (int)luaL_optinteger(L, 2, 1);
lua_settop(L, 1);
if (lua_type(L, 1) == LUA_TSTRING && level > 0) {
luaL_where(L, level); /* add extra information */
lua_pushvalue(L, 1);
lua_concat(L, 2);
}
return lua_error(L);
}
static int luaB_getmetatable (lua_State *L) {
luaL_checkany(L, 1);
if (!lua_getmetatable(L, 1)) {
lua_pushnil(L);
return 1; /* no metatable */
}
luaL_getmetafield(L, 1, "__metatable");
return 1; /* returns either __metatable field (if present) or metatable */
}
static int luaB_setmetatable (lua_State *L) {
int t = lua_type(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL))
return luaL_error(L, "cannot change a protected metatable");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1;
}
static int luaB_rawequal (lua_State *L) {
luaL_checkany(L, 1);
luaL_checkany(L, 2);
lua_pushboolean(L, lua_rawequal(L, 1, 2));
return 1;
}
static int luaB_rawlen (lua_State *L) {
int t = lua_type(L, 1);
luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
"table or string");
lua_pushinteger(L, lua_rawlen(L, 1));
return 1;
}
static int luaB_rawget (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_rawget(L, 1);
return 1;
}
static int luaB_rawset (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
luaL_checkany(L, 3);
lua_settop(L, 3);
lua_rawset(L, 1);
return 1;
}
static int pushmode (lua_State *L, int oldmode) {
lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental"
: "generational");
return 1;
}
static int luaB_collectgarbage (lua_State *L) {
static const char *const opts[] = {"stop", "restart", "collect",
"count", "step", "setpause", "setstepmul",
"isrunning", "generational", "incremental", NULL};
static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
switch (o) {
case LUA_GCCOUNT: {
int k = lua_gc(L, o);
int b = lua_gc(L, LUA_GCCOUNTB);
lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024));
return 1;
}
case LUA_GCSTEP: {
int step = (int)luaL_optinteger(L, 2, 0);
int res = lua_gc(L, o, step);
lua_pushboolean(L, res);
return 1;
}
case LUA_GCSETPAUSE:
case LUA_GCSETSTEPMUL: {
int p = (int)luaL_optinteger(L, 2, 0);
int previous = lua_gc(L, o, p);
lua_pushinteger(L, previous);
return 1;
}
case LUA_GCISRUNNING: {
int res = lua_gc(L, o);
lua_pushboolean(L, res);
return 1;
}
case LUA_GCGEN: {
int minormul = (int)luaL_optinteger(L, 2, 0);
int majormul = (int)luaL_optinteger(L, 3, 0);
return pushmode(L, lua_gc(L, o, minormul, majormul));
}
case LUA_GCINC: {
int pause = (int)luaL_optinteger(L, 2, 0);
int stepmul = (int)luaL_optinteger(L, 3, 0);
int stepsize = (int)luaL_optinteger(L, 4, 0);
return pushmode(L, lua_gc(L, o, pause, stepmul, stepsize));
}
default: {
int res = lua_gc(L, o);
lua_pushinteger(L, res);
return 1;
}
}
}
static int luaB_type (lua_State *L) {
int t = lua_type(L, 1);
luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
lua_pushstring(L, lua_typename(L, t));
return 1;
}
static int luaB_next (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2); /* create a 2nd argument if there isn't one */
if (lua_next(L, 1))
return 2;
else {
lua_pushnil(L);
return 1;
}
}
static int luaB_pairs (lua_State *L) {
luaL_checkany(L, 1);
if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */
lua_pushcfunction(L, luaB_next); /* will return generator, */
lua_pushvalue(L, 1); /* state, */
lua_pushnil(L); /* and initial value */
}
else {
lua_pushvalue(L, 1); /* argument 'self' to metamethod */
lua_call(L, 1, 3); /* get 3 values from metamethod */
}
return 3;
}
/*
** Traversal function for 'ipairs'
*/
static int ipairsaux (lua_State *L) {
lua_Integer i = luaL_checkinteger(L, 2) + 1;
lua_pushinteger(L, i);
return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
}
/*
** 'ipairs' function. Returns 'ipairsaux', given "table", 0.
** (The given "table" may not be a table.)
*/
static int luaB_ipairs (lua_State *L) {
luaL_checkany(L, 1);
lua_pushcfunction(L, ipairsaux); /* iteration function */
lua_pushvalue(L, 1); /* state */
lua_pushinteger(L, 0); /* initial value */
return 3;
}
static int load_aux (lua_State *L, int status, int envidx) {
if (l_likely(status == LUA_OK)) {
if (envidx != 0) { /* 'env' parameter? */
lua_pushvalue(L, envidx); /* environment for loaded function */
if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
lua_pop(L, 1); /* remove 'env' if not used by previous call */
}
return 1;
}
else { /* error (message is on top of the stack) */
luaL_pushfail(L);
lua_insert(L, -2); /* put before error message */
return 2; /* return fail plus error message */
}
}
static int luaB_loadfile (lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL);
const char *mode = luaL_optstring(L, 2, NULL);
int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
int status = luaL_loadfilex(L, fname, mode);
return load_aux(L, status, env);
}
/*
** {======================================================
** Generic Read function
** =======================================================
*/
/*
** reserved slot, above all arguments, to hold a copy of the returned
** string to avoid it being collected while parsed. 'load' has four
** optional arguments (chunk, source name, mode, and environment).
*/
#define RESERVEDSLOT 5
/*
** Reader for generic 'load' function: 'lua_load' uses the
** stack for internal stuff, so the reader cannot change the
** stack top. Instead, it keeps its resulting string in a
** reserved slot inside the stack.
*/
static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
(void)(ud); /* not used */
luaL_checkstack(L, 2, "too many nested functions");
lua_pushvalue(L, 1); /* get function */
lua_call(L, 0, 1); /* call it */
if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* pop result */
*size = 0;
return NULL;
}
else if (l_unlikely(!lua_isstring(L, -1)))
luaL_error(L, "reader function must return a string");
lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
return lua_tolstring(L, RESERVEDSLOT, size);
}
static int luaB_load (lua_State *L) {
int status;
size_t l;
const char *s = lua_tolstring(L, 1, &l);
const char *mode = luaL_optstring(L, 3, "bt");
int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
if (s != NULL) { /* loading a string? */
const char *chunkname = luaL_optstring(L, 2, s);
status = luaL_loadbufferx(L, s, l, chunkname, mode);
}
else { /* loading from a reader function */
const char *chunkname = luaL_optstring(L, 2, "=(load)");
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, RESERVEDSLOT); /* create reserved slot */
status = lua_load(L, generic_reader, NULL, chunkname, mode);
}
return load_aux(L, status, env);
}
/* }====================================================== */
static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
(void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */
return lua_gettop(L) - 1;
}
static int luaB_dofile (lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL);
lua_settop(L, 1);
if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK))
return lua_error(L);
lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
return dofilecont(L, 0, 0);
}
static int luaB_assert (lua_State *L) {
if (l_likely(lua_toboolean(L, 1))) /* condition is true? */
return lua_gettop(L); /* return all arguments */
else { /* error */
luaL_checkany(L, 1); /* there must be a condition */
lua_remove(L, 1); /* remove it */
lua_pushliteral(L, "assertion failed!"); /* default message */
lua_settop(L, 1); /* leave only message (default if no other one) */
return luaB_error(L); /* call 'error' */
}
}
static int luaB_select (lua_State *L) {
int n = lua_gettop(L);
if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
lua_pushinteger(L, n-1);
return 1;
}
else {
lua_Integer i = luaL_checkinteger(L, 1);
if (i < 0) i = n + i;
else if (i > n) i = n;
luaL_argcheck(L, 1 <= i, 1, "index out of range");
return n - (int)i;
}
}
/*
** Continuation function for 'pcall' and 'xpcall'. Both functions
** already pushed a 'true' before doing the call, so in case of success
** 'finishpcall' only has to return everything in the stack minus
** 'extra' values (where 'extra' is exactly the number of items to be
** ignored).
*/
static int finishpcall (lua_State *L, int status, lua_KContext extra) {
if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */
lua_pushboolean(L, 0); /* first result (false) */
lua_pushvalue(L, -2); /* error message */
return 2; /* return false, msg */
}
else
return lua_gettop(L) - (int)extra; /* return all results */
}
static int luaB_pcall (lua_State *L) {
int status;
luaL_checkany(L, 1);
lua_pushboolean(L, 1); /* first result if no errors */
lua_insert(L, 1); /* put it in place */
status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
return finishpcall(L, status, 0);
}
/*
** Do a protected call with error handling. After 'lua_rotate', the
** stack will have <f, err, true, f, [args...]>; so, the function passes
** 2 to 'finishpcall' to skip the 2 first values when returning results.
*/
static int luaB_xpcall (lua_State *L) {
int status;
int n = lua_gettop(L);
luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */
lua_pushboolean(L, 1); /* first result */
lua_pushvalue(L, 1); /* function */
lua_rotate(L, 3, 2); /* move them below function's arguments */
status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
return finishpcall(L, status, 2);
}
static int luaB_tostring (lua_State *L) {
luaL_checkany(L, 1);
luaL_tolstring(L, 1, NULL);
return 1;
}
static const luaL_Reg base_funcs[] = {
{"assert", luaB_assert},
{"collectgarbage", luaB_collectgarbage},
{"dofile", luaB_dofile},
{"error", luaB_error},
{"getmetatable", luaB_getmetatable},
{"ipairs", luaB_ipairs},
{"loadfile", luaB_loadfile},
{"load", luaB_load},
{"next", luaB_next},
{"pairs", luaB_pairs},
{"pcall", luaB_pcall},
{"print", luaB_print},
{"warn", luaB_warn},
{"rawequal", luaB_rawequal},
{"rawlen", luaB_rawlen},
{"rawget", luaB_rawget},
{"rawset", luaB_rawset},
{"select", luaB_select},
{"setmetatable", luaB_setmetatable},
{"tonumber", luaB_tonumber},
{"tostring", luaB_tostring},
{"type", luaB_type},
{"xpcall", luaB_xpcall},
/* placeholders */
{LUA_GNAME, NULL},
{"_VERSION", NULL},
{NULL, NULL}
};
LUAMOD_API int luaopen_base (lua_State *L) {
/* open lib into global table */
lua_pushglobaltable(L);
luaL_setfuncs(L, base_funcs, 0);
/* set global _G */
lua_pushvalue(L, -1);
lua_setfield(L, -2, LUA_GNAME);
/* set global _VERSION */
lua_pushliteral(L, LUA_VERSION);
lua_setfield(L, -2, "_VERSION");
return 1;
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff. Show more