summaryrefslogtreecommitdiff
path: root/libs/lua/LuaBridge/detail/LuaRef.h
blob: e726bcafe7bbf0af9bad1e7d99d434e24f1391de (plain)
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
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//------------------------------------------------------------------------------
/*
  https://github.com/vinniefalco/LuaBridge
  
  Copyright 2012, Vinnie Falco <vinnie.falco@gmail.com>
  Copyright 2008, Nigel Atkinson <suprapilot+LuaCode@gmail.com>

  License: The MIT License (http://www.opensource.org/licenses/mit-license.php)

  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.
*/
//==============================================================================

//------------------------------------------------------------------------------
/**
    Type tag for representing LUA_TNIL.

    Construct one of these using `Nil()` to represent a Lua nil. This is faster
    than creating a reference in the registry to nil. Example:

        LuaRef t (LuaRef::createTable (L));
        ...
        t ["k"] = Nil(); // assign nil
*/
struct Nil
{
};

//------------------------------------------------------------------------------
/**
    Lightweight reference to a Lua object.

    The reference is maintained for the lifetime of the C++ object.
*/
class LuaRef
{
private:
  class Proxy;
  friend struct Stack <Proxy>;

  //----------------------------------------------------------------------------
  /**
      Pop the Lua stack.

      Pops the specified number of stack items on destruction. We use this
      when returning objects, to avoid an explicit temporary variable, since
      the destructor executes after the return statement. For example:

          template <class U>
          U cast (lua_State* L)
          {
            StackPop p (L, 1);
            ...
            return U (); // dtor called after this line
          }

      @note The `StackPop` object must always be a named local variable.
  */
  class StackPop
  {
  public:
    /** Create a StackPop object.

        @param count The number of stack entries to pop on destruction.
    */
    StackPop (lua_State* L, int count)
      : m_L (L)
      , m_count (count)
    {
    }

    ~StackPop ()
    {
      lua_pop (m_L, m_count);
    }

  private:
    lua_State* m_L;
    int m_count;
  };

  //----------------------------------------------------------------------------
  /**
      A proxy for representing table values.
  */
  class Proxy
  {
  private:
    lua_State* m_L;
    int m_tableRef;
    int m_keyRef;

  public:
    //--------------------------------------------------------------------------
    /**
        Construct a Proxy from a table value.

        The table is in the registry, and the key is at the top of the stack.
        The key is popped off the stack.
    */
    Proxy (lua_State* L, int tableRef)
      : m_L (L)
      , m_tableRef (tableRef)
      , m_keyRef (luaL_ref (L, LUA_REGISTRYINDEX))
    {
    }

    //--------------------------------------------------------------------------
    /**
        Create a Proxy via copy constructor.

        It is best to avoid code paths that invoke this, because it creates
        an extra temporary Lua reference. Typically this is done by passing
        the Proxy parameter as a `const` reference.
    */
    Proxy (Proxy const& other)
      : m_L (other.m_L)
      , m_tableRef (other.m_tableRef)
    {
      // If this assert goes off it means code is taking this path,
      // which is better avoided.
      //
      assert (0);

      lua_rawgeti (m_L, LUA_REGISTRYINDEX, other.m_keyRef);
      m_keyRef = luaL_ref (m_L, LUA_REGISTRYINDEX);
    }

    //--------------------------------------------------------------------------
    /**
        Destroy the proxy.

        This does not destroy the table value.
    */
    ~Proxy ()
    {
      luaL_unref (m_L, LUA_REGISTRYINDEX, m_keyRef);
    }

    //--------------------------------------------------------------------------
    /**
        Return a reference to the table value.
    */
    int createRef () const
    {
      push (m_L);
      return luaL_ref (m_L, LUA_REGISTRYINDEX);
    }

    //--------------------------------------------------------------------------
    /**
        Assign a new value to this table key.

        This may invoke metamethods.
    */
    template <class T>
    Proxy& operator= (T v)
    {
      StackPop p (m_L, 1);
      lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
      lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
      Stack <T>::push (m_L, v);
      lua_rawset (m_L, -3);
      return *this;
    }

    //--------------------------------------------------------------------------
    /**
        Assign a new value to this table key.

        The assignment is raw, no metamethods are invoked.
    */
    template <class T>
    Proxy& rawset (T v)
    {
      StackPop p (m_L, 1);
      lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
      lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
      Stack <T>::push (m_L, v);
      lua_settable (m_L, -3);
      return *this;
    }

    //==========================================================================
    //
    // This group of member functions mirrors the member functions in LuaRef.

    /** Retrieve the lua_State associated with the table value.
    */
    lua_State* state () const
    {
      return m_L;
    }

    //--------------------------------------------------------------------------
    /**
        Push the value onto the Lua stack.
    */
    void push (lua_State* L) const
    {
      assert (equalstates (L, m_L));
      lua_rawgeti (L, LUA_REGISTRYINDEX, m_tableRef);
      lua_rawgeti (L, LUA_REGISTRYINDEX, m_keyRef);
      lua_gettable (L, -2);
      lua_remove (L, -2); // remove the table
    }

    //--------------------------------------------------------------------------
    /**
        Determine the object type.

        The return values are the same as for `lua_type`.
    */
    int type () const
    {
      int result;
      push (m_L);
      result = lua_type (m_L, -1);
      lua_pop (m_L, 1);
      return result;
    }

    inline bool isNil () const { return type () == LUA_TNIL; }
    inline bool isNumber () const { return type () == LUA_TNUMBER; }
    inline bool isString () const { return type () == LUA_TSTRING; }
    inline bool isTable () const { return type () == LUA_TTABLE; }
    inline bool isFunction () const { return type () == LUA_TFUNCTION; }
    inline bool isUserdata () const { return type () == LUA_TUSERDATA; }
    inline bool isThread () const { return type () == LUA_TTHREAD; }
    inline bool isLightUserdata () const { return type () == LUA_TLIGHTUSERDATA; }

    //--------------------------------------------------------------------------
    /**
        Perform an explicit conversion.
    */
    template <class T>
    T cast () const
    {
      StackPop p (m_L, 1);
      push (m_L);

      // lua_gettop is used because Userdata::getClass() doesn't handle
      // negative stack indexes.
      //
      return Stack <T>::get (m_L, lua_gettop (m_L));
    }

    //--------------------------------------------------------------------------
    /**
        Universal implicit conversion operator.

        NOTE: Visual Studio 2010 and 2012 have a bug where this function
              is not used. See:

        http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/e30b2664-a92d-445c-9db2-e8e0fbde2014
        https://connect.microsoft.com/VisualStudio/feedback/details/771509/correct-code-doesnt-compile

            // This code snippet fails to compile in vs2010,vs2012
            struct S {
              template <class T> inline operator T () const { return T (); }
            };
            int main () {
              S () || false;
              return 0;
            }
    */
    template <class T>
    inline operator T () const
    {
      return cast <T> ();
    }

    //--------------------------------------------------------------------------
    /**
        Universal comparison operators.
    */
    /** @{ */
    template <class T>
    bool operator== (T rhs) const
    {
      StackPop p (m_L, 2);
      push (m_L);
      Stack <T>::push (m_L, rhs);
      return lua_compare (m_L, -2, -1, LUA_OPEQ) == 1;
    }

    template <class T>
    bool operator< (T rhs) const
    {
      StackPop p (m_L, 2);
      push (m_L);
      Stack <T>::push (m_L, rhs);
      return lua_compare (m_L, -2, -1, LUA_OPLT) == 1;
    }

    template <class T>
    bool operator<= (T rhs) const
    {
      StackPop p (m_L, 2);
      push (m_L);
      Stack <T>::push (m_L, rhs);
      return lua_compare (m_L, -2, -1, LUA_OPLE) == 1;
    }

    template <class T>
    bool operator> (T rhs) const
    {
      StackPop p (m_L, 2);
      push (m_L);
      Stack <T>::push (m_L, rhs);
      return lua_compare (m_L, -1, -2, LUA_OPLT) == 1;
    }

    template <class T>
    bool operator>= (T rhs) const
    {
      StackPop p (m_L, 2);
      push (m_L);
      Stack <T>::push (m_L, rhs);
      return lua_compare (m_L, -1, -2, LUA_OPLE) == 1;
    }

    template <class T>
    bool rawequal (T rhs) const
    {
      StackPop p (m_L, 2);
      push (m_L);
      Stack <T>::push (m_L, rhs);
      return lua_rawequal (m_L, -1, -2) == 1;
    }
    /** @} */

    //--------------------------------------------------------------------------
    /**
        Access a table value using a key.

        This invokes metamethods.
    */
    template <class T>
    Proxy operator[] (T key) const
    {
      return LuaRef (*this) [key];
    }

    //--------------------------------------------------------------------------
    /**
        Access a table value using a key.

        The operation is raw, metamethods are not invoked. The result is
        passed by value and may not be modified.
    */
    template <class T>
    LuaRef rawget (T key) const
    {
      StackPop (m_L, 1);
      push (m_L);
      Stack <T>::push (m_L, key);
      lua_rawget (m_L, -2);
      return LuaRef (m_L, FromStack ());
    }

    //--------------------------------------------------------------------------
    /**
        Append a value to the table.

        If the table is a sequence this will add another element to it.
    */
    template <class T>
    void append (T v) const
    {
      push (m_L);
      Stack <T>::push (m_L, v);
      luaL_ref (m_L, -2);
      lua_pop (m_L, 1);
    }

    //--------------------------------------------------------------------------
    /**
        Call the length operator.

        This is identical to applying the Lua # operator.
    */
    int length () const
    {
      StackPop p (m_L, 1);
      push (m_L);
      return get_length (m_L, -1);
    }

    //--------------------------------------------------------------------------
    /**
        Call Lua code.

        These overloads allow Lua code to be called with up to 8 parameters.
        The return value is provided as a LuaRef (which may be LUA_REFNIL).
        If an error occurs, a LuaException is thrown.
    */
    /** @{ */
    LuaRef const operator() () const
    {
      push (m_L);
      LuaException::pcall (m_L, 0, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1>
    LuaRef const operator() (P1 p1) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      LuaException::pcall (m_L, 1, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2>
    LuaRef const operator() (P1 p1, P2 p2) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      LuaException::pcall (m_L, 2, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2, class P3>
    LuaRef const operator() (P1 p1, P2 p2, P3 p3) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      Stack <P3>::push (m_L, p3);
      LuaException::pcall (m_L, 3, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2, class P3, class P4>
    LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      Stack <P3>::push (m_L, p3);
      Stack <P4>::push (m_L, p4);
      LuaException::pcall (m_L, 4, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2, class P3, class P4, class P5>
    LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      Stack <P3>::push (m_L, p3);
      Stack <P4>::push (m_L, p4);
      Stack <P5>::push (m_L, p5);
      LuaException::pcall (m_L, 5, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2, class P3, class P4, class P5, class P6>
    LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      Stack <P3>::push (m_L, p3);
      Stack <P4>::push (m_L, p4);
      Stack <P5>::push (m_L, p5);
      Stack <P6>::push (m_L, p6);
      LuaException::pcall (m_L, 6, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
    LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      Stack <P3>::push (m_L, p3);
      Stack <P4>::push (m_L, p4);
      Stack <P5>::push (m_L, p5);
      Stack <P6>::push (m_L, p6);
      Stack <P7>::push (m_L, p7);
      LuaException::pcall (m_L, 7, 1);
      return LuaRef (m_L, FromStack ());
    }

    template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
    LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) const
    {
      push (m_L);
      Stack <P1>::push (m_L, p1);
      Stack <P2>::push (m_L, p2);
      Stack <P3>::push (m_L, p3);
      Stack <P4>::push (m_L, p4);
      Stack <P5>::push (m_L, p5);
      Stack <P6>::push (m_L, p6);
      Stack <P7>::push (m_L, p7);
      Stack <P8>::push (m_L, p8);
      LuaException::pcall (m_L, 8, 1);
      return LuaRef (m_L, FromStack ());
    }
    /** @} */

    //==========================================================================
  };

private:
  friend struct Stack <LuaRef>;

  //----------------------------------------------------------------------------
  /**
      Type tag for stack construction.
  */
  struct FromStack { };

  //----------------------------------------------------------------------------
  /**
      Create a reference to an object at the top of the Lua stack and pop it.

      This constructor is private and not invoked directly.
      Instead, use the `fromStack` function.

      @note The object is popped.
  */
  LuaRef (lua_State* L, FromStack)
    : m_L (L)
  {
    m_ref = luaL_ref (m_L, LUA_REGISTRYINDEX);
  }

  //----------------------------------------------------------------------------
  /**
      Create a reference to an object on the Lua stack.

      This constructor is private and not invoked directly.
      Instead, use the `fromStack` function.

      @note The object is not popped.
  */
  LuaRef (lua_State* L, int index, FromStack)
    : m_L (L)
  {
    lua_pushvalue (m_L, index);
    m_ref = luaL_ref (m_L, LUA_REGISTRYINDEX);
  }

  //----------------------------------------------------------------------------

  // This type of construction is disallowed, since we don't have a `lua_State`.
  //
  template <class T>
  LuaRef (T)
  {
  }

  //----------------------------------------------------------------------------
  /**
      Create a reference to this ref.

      This is used internally.
  */
  int createRef () const
  {
    if (m_ref != LUA_REFNIL)
    {
      push (m_L);
      return luaL_ref (m_L, LUA_REGISTRYINDEX);
    }
    else
    {
      return LUA_REFNIL;
    }
  }

public:
  //----------------------------------------------------------------------------
  /**
      Create a nil reference.

      The LuaRef may be assigned later.
  */
  LuaRef (lua_State* L)
    : m_L (L)
    , m_ref (LUA_REFNIL)
  {
  }

  //----------------------------------------------------------------------------
  /**
      Create a reference to a value.
  */
  template <class T>
  LuaRef (lua_State* L, T v)
    : m_L (L)
  {
    Stack <T>::push (m_L, v);
    m_ref = luaL_ref (m_L, LUA_REGISTRYINDEX);
  }

  //----------------------------------------------------------------------------
  /**
      Create a reference to a table value.
  */
  LuaRef (Proxy const& v)
    : m_L (v.state ())
    , m_ref (v.createRef ())
  {
  }

  //----------------------------------------------------------------------------
  /**
      Create a new reference to an existing reference.
  */
  LuaRef (LuaRef const& other)
    : m_L (other.m_L)
    , m_ref (other.createRef ())
  {
  }

  //----------------------------------------------------------------------------
  /**
      Destroy a reference.

      The corresponding Lua registry reference will be released.

      @note If the state refers to a thread, it is the responsibility of the
            caller to ensure that the thread still exists when the LuaRef
            is destroyed.
  */
  ~LuaRef ()
  {
    luaL_unref (m_L, LUA_REGISTRYINDEX, m_ref);
  }

  //----------------------------------------------------------------------------
  /**
      Return a LuaRef from a stack item.

      The stack item is not popped.
  */
  static LuaRef fromStack (lua_State* L, int index)
  {
    lua_pushvalue (L, index);
    return LuaRef (L, FromStack ());
  }

  //----------------------------------------------------------------------------
  /**
      Create a new empty table and return a reference to it.

      It is also possible to use the free function `newTable`.

      @see ::getGlobal
  */
  static LuaRef newTable (lua_State* L)
  {
    lua_newtable (L);
    return LuaRef (L, FromStack ());
  }

  //----------------------------------------------------------------------------
  /**
      Return a reference to a named global.

      It is also possible to use the free function `getGlobal`.

      @see ::getGlobal
  */
  static LuaRef getGlobal (lua_State *L, char const* name)
  {
    lua_getglobal (L, name);
    return LuaRef (L, FromStack ());
  }

  //----------------------------------------------------------------------------
  /**
      Assign a different value to this LuaRef.
  */
  template <class T>
  LuaRef& operator= (T rhs)
  {
    luaL_unref (m_L, LUA_REGISTRYINDEX, m_ref);
    Stack <T>::push (m_L, rhs);
    m_ref = luaL_ref (m_L, LUA_REGISTRYINDEX);
    return *this;
  }

  //----------------------------------------------------------------------------
  /**
      Assign another LuaRef to this LuaRef.
  */
  LuaRef& operator= (LuaRef const& rhs)
  {
    luaL_unref (m_L, LUA_REGISTRYINDEX, m_ref);
    rhs.push (m_L);
    m_L = rhs.state ();
    m_ref = luaL_ref (m_L, LUA_REGISTRYINDEX);
    return *this;
  }

  //----------------------------------------------------------------------------
  /**
      converts to a string using luas tostring function
  */
  std::string tostring() const
  {
    lua_getglobal (m_L, "tostring");
    push (m_L);
    lua_call (m_L, 1, 1);
    const char* str = lua_tostring(m_L, 1);
    lua_pop(m_L, 1);
    return std::string(str);
  }

  //----------------------------------------------------------------------------
  /**
      Print a text description of the value to a stream.

      This is used for diagnostics.
  */
  void print (std::ostream& os) const
  {
    switch (type ())
    {
    case LUA_TNIL:
      os << "nil";
      break;

    case LUA_TNUMBER:
      os << cast <lua_Number> ();
      break;

    case LUA_TBOOLEAN:
      os << (cast <bool> () ? "true" : "false");
      break;

    case LUA_TSTRING:
      os << '"' << cast <std::string> () << '"';
      break;

    case LUA_TTABLE:
      os << "table: " << tostring();
      break;

    case LUA_TFUNCTION:
      os << "function: " << tostring();
      break;

    case LUA_TUSERDATA:
      os << "userdata: " << tostring();
      break;

    case LUA_TTHREAD:
      os << "thread: " << tostring();
      break;

    case LUA_TLIGHTUSERDATA:
      os << "lightuserdata: " << tostring();
      break;

    default:
      os << "unknown";
      break;
    }
  }

  //============================================================================
  //
  // This group of member functions is mirrored in Proxy
  //

  /** Retrieve the lua_State associated with the reference.
  */
  lua_State* state () const
  {
    return m_L;
  }

  //----------------------------------------------------------------------------
  /**
      Place the object onto the Lua stack.
  */
  void push (lua_State* L) const
  {
    assert (equalstates (L, m_L));
    lua_rawgeti (L, LUA_REGISTRYINDEX, m_ref);
  }

  //----------------------------------------------------------------------------
  /**
      Pop the top of Lua stack and assign the ref to m_ref
  */
  void pop (lua_State* L)
  {
    assert (equalstates (L, m_L));
    luaL_unref (m_L, LUA_REGISTRYINDEX, m_ref);
    m_ref = luaL_ref (m_L, LUA_REGISTRYINDEX);
  }

  //----------------------------------------------------------------------------
  /**
      Determine the object type.

      The return values are the same as for `lua_type`.
  */
  /** @{ */
  int type () const
  {
    int result;
    if (m_ref != LUA_REFNIL)
    {
      push (m_L);
      result = lua_type (m_L, -1);
      lua_pop (m_L, 1);
    }
    else
    {
      result = LUA_TNIL;
    }

    return result;
  }

  // should never happen
  //inline bool isNone () const { return m_ref == LUA_NOREF; }

  inline bool isNil () const { return type () == LUA_TNIL; }
  inline bool isNumber () const { return type () == LUA_TNUMBER; }
  inline bool isString () const { return type () == LUA_TSTRING; }
  inline bool isTable () const { return type () == LUA_TTABLE; }
  inline bool isFunction () const { return type () == LUA_TFUNCTION; }
  inline bool isUserdata () const { return type () == LUA_TUSERDATA; }
  inline bool isThread () const { return type () == LUA_TTHREAD; }
  inline bool isLightUserdata () const { return type () == LUA_TLIGHTUSERDATA; }
  /** @} */

  //----------------------------------------------------------------------------
  /**
      Perform an explicit conversion.
  */
  template <class T>
  T cast () const
  {
    StackPop p (m_L, 1);
    push (m_L);

    // lua_gettop is used because Userdata::getClass() doesn't handle
    // negative stack indexes.
    //
    return Stack <T>::get (m_L, lua_gettop (m_L));
  }

  //----------------------------------------------------------------------------
  /**
      Universal implicit conversion operator.

      NOTE: Visual Studio 2010 and 2012 have a bug where this function
            is not used. See:

      http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/e30b2664-a92d-445c-9db2-e8e0fbde2014
      https://connect.microsoft.com/VisualStudio/feedback/details/771509/correct-code-doesnt-compile

          // This code snippet fails to compile in vs2010,vs2012
          struct S {
            template <class T> inline operator T () const { return T (); }
          };
          int main () {
            S () || false;
            return 0;
          }
  */
  template <class T>
  inline operator T () const
  {
    return cast <T> ();
  }

  //----------------------------------------------------------------------------
  /**
      Universal comparison operators.
  */
  /** @{ */
  template <class T>
  bool operator== (T rhs) const
  {
    StackPop p (m_L, 2);
    push (m_L);
    Stack <T>::push (m_L, rhs);
    return lua_compare (m_L, -2, -1, LUA_OPEQ) == 1;
  }

  template <class T>
  bool operator< (T rhs) const
  {
    StackPop p (m_L, 2);
    push (m_L);
    Stack <T>::push (m_L, rhs);
    return lua_compare (m_L, -2, -1, LUA_OPLT) == 1;
  }

  template <class T>
  bool operator<= (T rhs) const
  {
    StackPop p (m_L, 2);
    push (m_L);
    Stack <T>::push (m_L, rhs);
    return lua_compare (m_L, -2, -1, LUA_OPLE) == 1;
  }

  template <class T>
  bool operator> (T rhs) const
  {
    StackPop p (m_L, 2);
    push (m_L);
    Stack <T>::push (m_L, rhs);
    return lua_compare (m_L, -1, -2, LUA_OPLT) == 1;
  }

  template <class T>
  bool operator>= (T rhs) const
  {
    StackPop p (m_L, 2);
    push (m_L);
    Stack <T>::push (m_L, rhs);
    return lua_compare (m_L, -1, -2, LUA_OPLE) == 1;
  }

  template <class T>
  bool rawequal (T rhs) const
  {
    StackPop p (m_L, 2);
    push (m_L);
    Stack <T>::push (m_L, rhs);
    return lua_rawequal (m_L, -1, -2) == 1;
  }
  /** @} */

  //----------------------------------------------------------------------------
  /**
      Append a value to the table.

      If the table is a sequence this will add another element to it.
  */
  template <class T>
  void append (T v) const
  {
    push (m_L);
    Stack <T>::push (m_L, v);
    luaL_ref (m_L, -2);
    lua_pop (m_L, 1);
  }

  //----------------------------------------------------------------------------
  /**
      Call the length operator.

      This is identical to applying the Lua # operator.
  */
  int length () const
  {
    StackPop p (m_L, 1);
    push (m_L);
    return get_length (m_L, -1);
  }

  //----------------------------------------------------------------------------
  /**
      Access a table value using a key.

      This invokes metamethods.
  */
  template <class T>
  Proxy operator[] (T key) const
  {
    Stack <T>::push (m_L, key);
    return Proxy (m_L, m_ref);
  }

  //----------------------------------------------------------------------------
  /**
      Call Lua code.

      These overloads allow Lua code to be called with up to 8 parameters.
      The return value is provided as a LuaRef (which may be LUA_REFNIL).
      If an error occurs, a LuaException is thrown.
  */
  /** @{ */
  LuaRef const operator() () const
  {
    push (m_L);
    LuaException::pcall (m_L, 0, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1>
  LuaRef const operator() (P1 p1) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    LuaException::pcall (m_L, 1, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2>
  LuaRef const operator() (P1 p1, P2 p2) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    LuaException::pcall (m_L, 2, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2, class P3>
  LuaRef const operator() (P1 p1, P2 p2, P3 p3) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    Stack <P3>::push (m_L, p3);
    LuaException::pcall (m_L, 3, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2, class P3, class P4>
  LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    Stack <P3>::push (m_L, p3);
    Stack <P4>::push (m_L, p4);
    LuaException::pcall (m_L, 4, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2, class P3, class P4, class P5>
  LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    Stack <P3>::push (m_L, p3);
    Stack <P4>::push (m_L, p4);
    Stack <P5>::push (m_L, p5);
    LuaException::pcall (m_L, 5, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2, class P3, class P4, class P5, class P6>
  LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    Stack <P3>::push (m_L, p3);
    Stack <P4>::push (m_L, p4);
    Stack <P5>::push (m_L, p5);
    Stack <P6>::push (m_L, p6);
    LuaException::pcall (m_L, 6, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
  LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    Stack <P3>::push (m_L, p3);
    Stack <P4>::push (m_L, p4);
    Stack <P5>::push (m_L, p5);
    Stack <P6>::push (m_L, p6);
    Stack <P7>::push (m_L, p7);
    LuaException::pcall (m_L, 7, 1);
    return LuaRef (m_L, FromStack ());
  }

  template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
  LuaRef const operator() (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) const
  {
    push (m_L);
    Stack <P1>::push (m_L, p1);
    Stack <P2>::push (m_L, p2);
    Stack <P3>::push (m_L, p3);
    Stack <P4>::push (m_L, p4);
    Stack <P5>::push (m_L, p5);
    Stack <P6>::push (m_L, p6);
    Stack <P7>::push (m_L, p7);
    Stack <P8>::push (m_L, p8);
    LuaException::pcall (m_L, 8, 1);
    return LuaRef (m_L, FromStack ());
  }
  /** @} */

  //============================================================================

private:
  lua_State* m_L;
  int m_ref;
};

//------------------------------------------------------------------------------
/**
    Stack specialization for Nil
*/
template <>
struct Stack <Nil>
{
public:
  static inline void push (lua_State* L, Nil)
  {
    lua_pushnil (L);
  }
};

//------------------------------------------------------------------------------
/**
    Stack specialization for LuaRef.
*/
template <>
struct Stack <LuaRef>
{
public:
  // The value is const& to prevent a copy construction.
  //
  static inline void push (lua_State* L, LuaRef const& v)
  {
    v.push (L);
  }

  static inline LuaRef get (lua_State* L, int index)
  {
    return LuaRef (L, index, LuaRef::FromStack ());
  }
};

//------------------------------------------------------------------------------
/**
    Stack specialization for Proxy.
*/
template <>
struct Stack <LuaRef::Proxy>
{
public:
  // The value is const& to prevent a copy construction.
  //
  static inline void push (lua_State* L, LuaRef::Proxy const& v)
  {
    v.push (L);
  }
};

//------------------------------------------------------------------------------
/**
    Create a reference to a new, empty table.

    This is a syntactic abbreviation for LuaRef::newTable().
*/
inline LuaRef newTable (lua_State* L)
{
  return LuaRef::newTable (L);
}

//------------------------------------------------------------------------------
/**
    Create a reference to a value in the global table.

    This is a syntactic abbreviation for LuaRef::getGlobal().
*/
inline LuaRef getGlobal (lua_State *L, char const* name)
{
  return LuaRef::getGlobal (L, name);
}

//------------------------------------------------------------------------------
/**
    Write a LuaRef to a stream.

    This allows LuaRef and table proxies to work with streams.
*/
inline std::ostream& operator<< (std::ostream& os, LuaRef const& ref)
{
  ref.print (os);
  return os;
}

//------------------------------------------------------------------------------

// more C++-like cast syntax
//
template<class T>
inline T LuaRef_cast(LuaRef const& lr)
{
  return lr.cast<T>();
}