开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 2

紫星/LuaVM

forked from abin-liu/LuaVM
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (2)
master
main
master
分支 (2)
master
main
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (2)
master
main
Lua.cs 31.94 KB
一键复制 编辑 原始数据 按行查看 历史
abin-liu 提交于 2021年06月11日 10:57 +08:00 . Initial commit on Gitee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using LuaInterface.Event;
using LuaInterface.Method;
using LuaInterface.Exceptions;
using LuaInterface.Extensions;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
/*
* Main class of LuaInterface
* Object-oriented wrapper to Lua API
*
* Author: Fabio Mascarenhas
* Version: 1.0
*
* // steffenj: important changes in Lua class:
* - removed all Open*Lib() functions
* - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs)
* */
//[CLSCompliant(true)]
public class Lua : IDisposable
{
#region lua debug functions
/// <summary>
/// Event that is raised when an exception occures during a hook call.
/// </summary>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<HookExceptionEventArgs> HookException;
/// <summary>
/// Event when lua hook callback is called
/// </summary>
/// <remarks>
/// Is only raised if SetDebugHook is called before.
/// </remarks>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<DebugHookEventArgs> DebugHook;
/// <summary>
/// lua hook calback delegate
/// </summary>
/// <author>Reinhard Ostermeier</author>
private LuaCore.lua_Hook hookCallback = null;
#endregion
#region Globals auto-complete
private readonly List<string> globals = new List<string>();
private bool globalsSorted;
#endregion
private /*readonly */ LuaCore.lua_State luaState;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
private LuaCore.lua_CFunction panicCallback;
private ObjectTranslator translator;
/// <summary>
/// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects
/// </summary>
//private object luaLock = new object();
private bool _StatePassed;
private bool executing;
static string init_luanet =
"local metatable = {} \n" +
"local import_type = luanet.import_type \n" +
"local load_assembly = luanet.load_assembly \n" +
" \n" +
"-- Lookup a .NET identifier component. \n" +
"function metatable:__index(key) -- key is e.g. \"Form\" \n" +
" -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n" +
" local fqn = ((rawget(self, \".fqn\") and rawget(self, \".fqn\") .. \n" +
" \".\") or \"\") .. key \n" +
" \n" +
" -- Try to find either a luanet function or a CLR type \n" +
" local obj = rawget(luanet, key) or import_type(fqn) \n" +
" \n" +
" -- If key is neither a luanet function or a CLR type, then it is simply \n" +
" -- an identifier component. \n" +
" if obj == nil then \n" +
" -- It might be an assembly, so we load it too. \n" +
" load_assembly(fqn) \n" +
" obj = { [\".fqn\"] = fqn } \n" +
" setmetatable(obj, metatable) \n" +
" end \n" +
" \n" +
" -- Cache this lookup \n" +
" rawset(self, key, obj) \n" +
" return obj \n" +
"end \n" +
" \n" +
"-- A non-type has been called; e.g. foo = System.Foo() \n" +
"function metatable:__call(...) \n" +
" error(\"No such type: \" .. rawget(self, \".fqn\"), 2) \n" +
"end \n" +
" \n" +
"-- This is the root of the .NET namespace \n" +
"luanet[\".fqn\"] = false \n" +
"setmetatable(luanet, metatable) \n" +
" \n" +
"-- Preload the mscorlib assembly \n" +
"luanet.load_assembly(\"mscorlib\") \n";
#region Globals auto-complete
/// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance
/// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks>
public IEnumerable<string> Globals
{
get
{
// Only sort list when necessary
if(!globalsSorted)
{
globals.Sort();
globalsSorted = true;
}
return globals;
}
}
#endregion
public Lua()
{
luaState = LuaLib.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//LuaLib.luaopen_base(luaState); // steffenj: luaopen_* no longer used
LuaLib.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here)
LuaLib.lua_pushstring(luaState, "LUAINTERFACE LOADED");
LuaLib.lua_pushboolean(luaState, true);
LuaLib.lua_settable(luaState, (int)LuaIndexes.Registry);
LuaLib.lua_newtable(luaState);
LuaLib.lua_setglobal(luaState, "luanet");
LuaLib.lua_pushvalue(luaState, (int)LuaIndexes.Globals);
LuaLib.lua_getglobal(luaState, "luanet");
LuaLib.lua_pushstring(luaState, "getmetatable");
LuaLib.lua_getglobal(luaState, "getmetatable");
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_replace(luaState, (int)LuaIndexes.Globals);
translator = new ObjectTranslator(this, luaState);
LuaLib.lua_replace(luaState, (int)LuaIndexes.Globals);
LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
// We need to keep this in a managed reference so the delegate doesn't get garbage collected
panicCallback = new LuaCore.lua_CFunction(PanicCallback);
LuaLib.lua_atpanic(luaState, panicCallback);
//LuaLib.lua_atlock(luaState, lockCallback = new LuaCore.lua_CFunction(LockCallback));
//LuaLib.lua_atunlock(luaState, unlockCallback = new LuaCore.lua_CFunction(UnlockCallback));
}
/*
* CAUTION: LuaInterface.Lua instances can't share the same lua state!
*/
public Lua(LuaCore.lua_State lState)
{
LuaLib.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaLib.lua_gettable(lState, (int)LuaIndexes.Registry);
if(LuaLib.lua_toboolean(lState, -1))
{
LuaLib.lua_settop(lState, -2);
throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
}
else
{
LuaLib.lua_settop(lState, -2);
LuaLib.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaLib.lua_pushboolean(lState, true);
LuaLib.lua_settable(lState, (int)LuaIndexes.Registry);
luaState = lState;
LuaLib.lua_pushvalue(lState, (int)LuaIndexes.Globals);
LuaLib.lua_getglobal(lState, "luanet");
LuaLib.lua_pushstring(lState, "getmetatable");
LuaLib.lua_getglobal(lState, "getmetatable");
LuaLib.lua_settable(lState, -3);
LuaLib.lua_replace(lState, (int)LuaIndexes.Globals);
translator = new ObjectTranslator(this, luaState);
LuaLib.lua_replace(lState, (int)LuaIndexes.Globals);
LuaLib.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
}
_StatePassed = true;
}
/// <summary>
/// Called for each lua_lock call
/// </summary>
/// <param name = "luaState"></param>
/// Not yet used
/*int LockCallback(LuaCore.lua_State luaState)
{
// Monitor.Enter(luaLock);
return 0;
}*/
/// <summary>
/// Called for each lua_unlock call
/// </summary>
/// <param name = "luaState"></param>
/// Not yet used
/*int UnlockCallback(LuaCore.lua_State luaState)
{
// Monitor.Exit(luaLock);
return 0;
}*/
public void Close()
{
if(_StatePassed)
return;
////// if(luaState != LuaCore.lua_State.Zero)
if(!luaState.IsNull())
LuaCore.lua_close(luaState);
//luaState = LuaCore.lua_State.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id = 44593&forum_id = 146
}
static int PanicCallback(LuaCore.lua_State luaState)
{
// string desc = LuaLib.lua_tostring(luaState, 1);
string reason = string.Format("unprotected error in call to Lua API ({0})", LuaLib.lua_tostring(luaState, -1));
// lua_tostring(L, -1);
throw new LuaException(reason);
}
/// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
/// </summary>
/// <exception cref = "LuaScriptException">Thrown if the script caused an exception</exception>
private void ThrowExceptionFromError(int oldTop)
{
object err = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, oldTop);
// A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
var luaEx = err as LuaScriptException;
if(!luaEx.IsNull())
throw luaEx;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if(err.IsNull())
err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), string.Empty);
}
/// <summary>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name = "e">null for no pending exception</param>
internal int SetPendingException(Exception e)
{
var caughtExcept = e;
if(!caughtExcept.IsNull())
{
translator.throwError(luaState, caughtExcept);
LuaLib.lua_pushnil(luaState);
return 1;
}
else
return 0;
}
/// <summary>
///
/// </summary>
/// <param name = "chunk"></param>
/// <param name = "name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name)
{
int oldTop = LuaLib.lua_gettop(luaState);
executing = true;
try
{
if(LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop);
}
finally
{
executing = false;
}
var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/// <summary>
///
/// </summary>
/// <param name = "fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = LuaLib.lua_gettop(luaState);
if(LuaLib.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop);
var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/*
* Excutes a Lua chunk and returns all the chunk's return
* values in an array
*/
public object[] DoString(string chunk)
{
int oldTop = LuaLib.lua_gettop(luaState);
if(LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{
executing = true;
try
{
if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally
{
executing = false;
}
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary>
/// <param name = "chunk">Chunk to execute</param>
/// <param name = "chunkName">Name to associate with the chunk</param>
/// <returns></returns>
public object[] DoString(string chunk, string chunkName)
{
int oldTop = LuaLib.lua_gettop(luaState);
executing = true;
if(LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
{
try
{
if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally
{
executing = false;
}
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/*
* Excutes a Lua file and returns all the chunk's return
* values in an array
*/
public object[] DoFile(string fileName)
{
int oldTop = LuaLib.lua_gettop(luaState);
if(LuaLib.luaL_loadfile(luaState, fileName) == 0)
{
executing = true;
try
{
if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally
{
executing = false;
}
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/*
* Indexer for global variables from the LuaInterpreter
* Supports navigation of tables by using . operator
*/
public object this[string fullPath]
{
get
{
object returnValue = null;
int oldTop = LuaLib.lua_gettop(luaState);
string[] path = fullPath.Split(new char[] { '.' });
LuaLib.lua_getglobal(luaState, path[0]);
returnValue = translator.getObject(luaState, -1);
if(path.Length>1)
{
string[] remainingPath = new string[path.Length-1];
Array.Copy(path, 1, remainingPath, 0, path.Length-1);
returnValue = getObject(remainingPath);
}
LuaLib.lua_settop(luaState, oldTop);
return returnValue;
}
set
{
int oldTop = LuaLib.lua_gettop(luaState);
string[] path = fullPath.Split(new char[] { '.' });
if(path.Length == 1)
{
translator.push(luaState, value);
LuaLib.lua_setglobal(luaState, fullPath);
}
else
{
LuaLib.lua_getglobal(luaState, path[0]);
string[] remainingPath = new string[path.Length-1];
Array.Copy(path, 1, remainingPath, 0, path.Length-1);
setObject(remainingPath, value);
}
LuaLib.lua_settop(luaState, oldTop);
// Globals auto-complete
if(value.IsNull())
{
// Remove now obsolete entries
globals.Remove(fullPath);
}
else
{
// Add new entries
if(!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0);
}
}
}
#region Globals auto-complete
/// <summary>
/// Adds an entry to <see cref = "globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <param name = "path">The index accessor path ot the entry</param>
/// <param name = "type">The type of the entry</param>
/// <param name = "recursionCounter">How deep have we gone with recursion?</param>
private void registerGlobal(string path, Type type, int recursionCounter)
{
// If the type is a global method, list it directly
if(type == typeof(LuaCore.lua_CFunction))
{
// Format for easy method invocation
globals.Add(path + "(");
}
// If the type is a class or an interface and recursion hasn't been running too long, list the members
else if((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
{
#region Methods
foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
// Exclude some generic .NET methods that wouldn't be very usefull in Lua
method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal))
{
// Format for easy method invocation
string command = path + ":" + method.Name + "(";
if(method.GetParameters().Length == 0) command += ")";
globals.Add(command);
}
}
#endregion
#region Fields
foreach(var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
{
// Go into recursion for members
registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1);
}
}
#endregion
#region Properties
foreach(var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
// Exclude some generic .NET properties that wouldn't be very usefull in Lua
&& property.Name != "Item")
{
// Go into recursion for members
registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
}
}
#endregion
}
else
globals.Add(path); // Otherwise simply add the element to the list
// List will need to be sorted on next access
globalsSorted = false;
}
#endregion
/*
* Navigates a table in the top of the stack, returning
* the value of the specified field
*/
internal object getObject(string[] remainingPath)
{
object returnValue = null;
for(int i = 0; i < remainingPath.Length; i++)
{
LuaLib.lua_pushstring(luaState, remainingPath[i]);
LuaLib.lua_gettable(luaState, -2);
returnValue = translator.getObject(luaState, -1);
if(returnValue.IsNull())
break;
}
return returnValue;
}
/*
* Gets a numeric global variable
*/
public double GetNumber(string fullPath)
{
return (double)this[fullPath];
}
/*
* Gets a string global variable
*/
public string GetString(string fullPath)
{
return this[fullPath].ToString();
}
/*
* Gets a table global variable
*/
public LuaTable GetTable(string fullPath)
{
return (LuaTable)this[fullPath];
}
/*
* Gets a table global variable as an object implementing
* the interfaceType interface
*/
public object GetTable(Type interfaceType, string fullPath)
{
return CodeGeneration.Instance.GetClassInstance(interfaceType, GetTable(fullPath));
}
/*
* Gets a function global variable
*/
public LuaFunction GetFunction(string fullPath)
{
object obj = this[fullPath];
return (obj is LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)obj, this) : (LuaFunction)obj);
}
/*
* Gets a function global variable as a delegate of
* type delegateType
*/
public Delegate GetFunction(Type delegateType, string fullPath)
{
return CodeGeneration.Instance.GetDelegate(delegateType, GetFunction(fullPath));
}
/*
* Calls the object as a function with the provided arguments,
* returning the function's returned values inside an array
*/
internal object[] callFunction(object function, object[] args)
{
return callFunction(function, args, null);
}
/*
* Calls the object as a function with the provided arguments and
* casting returned values to the types in returnTypes before returning
* them in an array
*/
internal object[] callFunction(object function, object[] args, Type[] returnTypes)
{
int nArgs = 0;
int oldTop = LuaLib.lua_gettop(luaState);
if(!LuaLib.lua_checkstack(luaState, args.Length+6))
throw new LuaException("Lua stack overflow");
translator.push(luaState, function);
if(!args.IsNull())
{
nArgs = args.Length;
for(int i = 0; i < args.Length; i++)
translator.push(luaState, args[i]);
}
executing = true;
try
{
int error = LuaLib.lua_pcall(luaState, nArgs, -1, 0);
if(error != 0)
ThrowExceptionFromError(oldTop);
}
finally
{
executing = false;
}
return !returnTypes.IsNull() ? translator.popValues(luaState, oldTop, returnTypes) : translator.popValues(luaState, oldTop);
}
/*
* Navigates a table to set the value of one of its fields
*/
internal void setObject(string[] remainingPath, object val)
{
for(int i = 0; i < remainingPath.Length-1; i++)
{
LuaLib.lua_pushstring(luaState, remainingPath[i]);
LuaLib.lua_gettable(luaState, -2);
}
LuaLib.lua_pushstring(luaState, remainingPath[remainingPath.Length-1]);
translator.push(luaState, val);
LuaLib.lua_settable(luaState, -3);
}
/*
* Creates a new table as a global variable or as a field
* inside an existing table
*/
public void NewTable(string fullPath)
{
string[] path = fullPath.Split(new char[] { '.' });
int oldTop = LuaLib.lua_gettop(luaState);
if(path.Length == 1)
{
LuaLib.lua_newtable(luaState);
LuaLib.lua_setglobal(luaState, fullPath);
}
else
{
LuaLib.lua_getglobal(luaState, path[0]);
for(int i = 1; i < path.Length-1; i++)
{
LuaLib.lua_pushstring(luaState, path[i]);
LuaLib.lua_gettable(luaState, -2);
}
LuaLib.lua_pushstring(luaState, path[path.Length-1]);
LuaLib.lua_newtable(luaState);
LuaLib.lua_settable(luaState, -3);
}
LuaLib.lua_settop(luaState, oldTop);
}
public ListDictionary GetTableDict(LuaTable table)
{
var dict = new ListDictionary();
int oldTop = LuaLib.lua_gettop(luaState);
translator.push(luaState, table);
LuaLib.lua_pushnil(luaState);
while(LuaLib.lua_next(luaState, -2) != 0)
{
dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, -2);
}
LuaLib.lua_settop(luaState, oldTop);
return dict;
}
/*
* Lets go of a previously allocated reference to a table, function
* or userdata
*/
#region lua debug functions
/// <summary>
/// Activates the debug hook
/// </summary>
/// <param name = "mask">Mask</param>
/// <param name = "count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author>
public int SetDebugHook(EventMasks mask, int count)
{
if(hookCallback.IsNull())
{
hookCallback = new LuaCore.lua_Hook(DebugHookCallback);
return LuaCore.lua_sethook(luaState, hookCallback, (int)mask, count);
}
return -1;
}
/// <summary>
/// Removes the debug hook
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int RemoveDebugHook()
{
hookCallback = null;
return LuaCore.lua_sethook(luaState, null, 0, 0);
}
/// <summary>
/// Gets the hook mask.
/// </summary>
/// <returns>hook mask</returns>
/// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask()
{
return (EventMasks)LuaCore.lua_gethookmask(luaState);
}
/// <summary>
/// Gets the hook count
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int GetHookCount()
{
return LuaCore.lua_gethookcount(luaState);
}
/// <summary>
/// Gets the stack entry on a given level
/// </summary>
/// <param name = "level">level</param>
/// <param name = "luaDebug">lua debug structure</param>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns>
/// <author>Reinhard Ostermeier</author>
/*public bool GetStack(int level, out LuaCore.lua_Debug luaDebug)
{
luaDebug = new LuaDebug();
LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaLib.lua_getstack(luaState, level, luaDebug) != 0;
}
finally
{
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}*/
/// <summary>
/// Gets info (see lua docs)
/// </summary>
/// <param name = "what">what (see lua docs)</param>
/// <param name = "luaDebug">lua debug structure</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
/*public int GetInfo(String what, ref LuaCore.lua_Debug luaDebug)
{
LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaLib.lua_getinfo(luaState, what, ld);
}
finally
{
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}*/
/// <summary>
/// Gets local (see lua docs)
/// </summary>
/// <param name = "luaDebug">lua debug structure</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public string GetLocal(LuaCore.lua_Debug luaDebug, int n)
{
return LuaCore.lua_getlocal(luaState, luaDebug, n).ToString();
}
/// <summary>
/// Sets local (see lua docs)
/// </summary>
/// <param name = "luaDebug">lua debug structure</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public string SetLocal(LuaCore.lua_Debug luaDebug, int n)
{
return LuaCore.lua_setlocal(luaState, luaDebug, n).ToString();
}
/// <summary>
/// Gets up value (see lua docs)
/// </summary>
/// <param name = "funcindex">see lua docs</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public string GetUpValue(int funcindex, int n)
{
return LuaCore.lua_getupvalue(luaState, funcindex, n).ToString();
}
/// <summary>
/// Sets up value (see lua docs)
/// </summary>
/// <param name = "funcindex">see lua docs</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public string SetUpValue(int funcindex, int n)
{
return LuaCore.lua_setupvalue(luaState, funcindex, n).ToString();
}
/// <summary>
/// Delegate that is called on lua hook callback
/// </summary>
/// <param name = "luaState">lua state</param>
/// <param name = "luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <author>Reinhard Ostermeier</author>
private void DebugHookCallback(LuaCore.lua_State luaState, LuaCore.lua_Debug luaDebug)
{
try
{
var temp = DebugHook;
if(!temp.IsNull())
temp(this, new DebugHookEventArgs(luaDebug));
}
catch(Exception ex)
{
OnHookException(new HookExceptionEventArgs(ex));
}
}
private void OnHookException(HookExceptionEventArgs e)
{
var temp = HookException;
if(!temp.IsNull())
temp(this, e);
}
/// <summary>
/// Pops a value from the lua stack.
/// </summary>
/// <returns>Returns the top value from the lua stack.</returns>
/// <author>Reinhard Ostermeier</author>
public object Pop()
{
int top = LuaLib.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0];
}
/// <summary>
/// Pushes a value onto the lua stack.
/// </summary>
/// <param name = "value">Value to push.</param>
/// <author>Reinhard Ostermeier</author>
public void Push(object value)
{
translator.push(luaState, value);
}
#endregion
internal void dispose(int reference)
{
if(!luaState.IsNull()) //Fix submitted by Qingrui Li
LuaLib.lua_unref(luaState, reference);
}
/*
* Gets a field of the table corresponding to the provided reference
* using rawget (do not use metatables)
*/
internal object rawGetObject(int reference, string field)
{
int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
LuaLib.lua_pushstring(luaState, field);
LuaLib.lua_rawget(luaState, -2);
object obj = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, oldTop);
return obj;
}
/*
* Gets a field of the table or userdata corresponding to the provided reference
*/
internal object getObject(int reference, string field)
{
int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
object returnValue = getObject(field.Split(new char[] {'.'}));
LuaLib.lua_settop(luaState, oldTop);
return returnValue;
}
/*
* Gets a numeric field of the table or userdata corresponding the the provided reference
*/
internal object getObject(int reference, object field)
{
int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
translator.push(luaState, field);
LuaLib.lua_gettable(luaState, -2);
object returnValue = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, oldTop);
return returnValue;
}
/*
* Sets a field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, string field, object val)
{
int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
setObject(field.Split(new char[] {'.'}), val);
LuaLib.lua_settop(luaState, oldTop);
}
/*
* Sets a numeric field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, object field, object val)
{
int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
translator.push(luaState, field);
translator.push(luaState, val);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_settop(luaState, oldTop);
}
/*
* Registers an object's method as a Lua function (global or table field)
* The method may have any signature
*/
public LuaFunction RegisterFunction(string path, object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id = 2859&forum_id = 145)
{
// We leave nothing on the stack when we are done
int oldTop = LuaLib.lua_gettop(luaState);
var wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
translator.push(luaState, new LuaCore.lua_CFunction(wrapper.call));
this[path] = translator.getObject(luaState, -1);
var f = GetFunction(path);
LuaLib.lua_settop(luaState, oldTop);
return f;
}
/*
* Compares the two values referenced by ref1 and ref2 for equality
*/
internal bool compareRef(int ref1, int ref2)
{
int top = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, ref1);
LuaLib.lua_getref(luaState, ref2);
int equal = LuaLib.lua_equal(luaState, -1, -2);
LuaLib.lua_settop(luaState, top);
return (equal != 0);
}
internal void pushCSFunction(LuaCore.lua_CFunction function)
{
translator.pushFunction(luaState, function);
}
#region IDisposable Members
public virtual void Dispose()
{
if(!translator.IsNull())
{
translator.pendingEvents.Dispose();
translator = null;
}
this.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
}
#endregion
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

基于C#的Lua虚拟机,包含Lua代码编辑器、图形化Lua运行环境,以及若干个内置Lua插件(实现常用的的Win32窗体操作、屏幕像素抓取与识别、键盘鼠标模拟输入等基础功能)。代码中包含插件开发API,可以通过开发插件的方法对Lua环境的功能进行无限扩充。
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/zixing/LuaVM.git
git@gitee.com:zixing/LuaVM.git
zixing
LuaVM
LuaVM
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /